【问题标题】:How to auto animate element every time when it changes position on the screen?每次在屏幕上更改位置时如何自动为元素设置动画?
【发布时间】:2021-02-03 18:31:04
【问题描述】:

我有 vue 项目。

每次页面上的某些元素因为 v-if 而消失时,页面的其余部分都会稍微重新排列。我希望它顺利进行。

所有元素都有:key属性。

示例: 我在一行中居中了 2 个盒子。当一个消失时,第二个仍然居中,因此改变位置。 image

如何处理?

编辑 1 我试过了:

    <div>
        <CompoentA :key=345 class="one-line" v-show="showComponentA" />
        <transition name="moving">
            <CompoentB class="one-line" :key=123 />
        </transition>
    </div>
.one-line { display: inline-table; }
.moving-move { transition: transform 1s; }

【问题讨论】:

  • 正如 devdgehog 提到的,v-if 正在删除这些项目。您应该考虑绑定类名,然后使用 CSS 转换为它们设置动画,绑定样式,或者考虑使用类似 masonry 的东西。 vuejs.org/v2/guide/class-and-style.html#Binding-Inline-Styles
  • @Djave 你能再描述一下吗?我只是在学习 css,不知道如何使用您的建议。

标签: css vue.js animation css-animations css-transitions


【解决方案1】:

v-if 将从 DOM 中删除元素,因此您无法为消失的组件设置动画。

如果你想为它们设置动画,你应该使用 v-show 代替(它们将隐藏在 DOM 中)。

【讨论】:

  • 好的,但即使我将 v-if 更改为 v-show,这也不起作用:(我更新了描述)
【解决方案2】:

我认为您需要“from”和“to”值来创建此动画。当您从 DOM 中删除元素时,其他元素将基于“内联”位置放置,因此没有值引用来创建过渡。 这里有一个类似的问题,有 height:0 和 height: auto 的过渡

How can I transition height: 0; to height: auto; using CSS?

我制作了一个示例来解决这个问题,使用宽度(大于内容)和不透明度为 0 的宽度 0 来隐藏内部内容。要运行此示例,只需单击项目,它将被“移除”(不透明度:0 和宽度:0),并且由于设置了初始宽度(80px),因此过渡有效。

new Vue({
    el: "#app",
  data: () => ({
    // yes, there is better ways, but let make this sample "simple"
    letters: ['a', 'b', 'c', 'd'],
    visible: {
        a: true,
        b: true,
        c: true,
        d: true,
    }
  })
})
#app {
  /* decoration, you can remove */
  width: 100%; 
  text-align: center;
  background-color: #f4f4f4;
}

.moving {
  /* margin and padding 0 
     because the width content will be set to 0
     if this element has a margin, when removed the margin still display the "space"
  */
  padding: 0; 
  margin: 0;
  font-size: 0; /* remove white space in DOM element */
  display: inline-block;
  opacity: 1;
  transition: width linear .2s;
  
  /* decoration, you can remove */
  width: 80px; 
  border: 1px dotted #ccc;
  cursor: pointer;
}

.moving-content {
  font-size: 18px; /* restore font size */
  display: inline-block;
  
  /* decoration, you can remove */
  background-color: #2af; 
  color: white;
  padding: 20px;
  box-sizing: border-box;
}

.moving.hidden {
  width: 0px;
  opacity: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
    <div v-for="letter in letters"
        :key="letter"
        :class="{ moving: true, hidden: !visible[letter] }" @click="visible[letter] = false">
        <span class="moving-content">
          {{ letter }}
        </span>
    </div>
</div>

参考资料:

https://stackoverflow.com/a/40785144/1724128

https://stackoverflow.com/a/53127208/1724128

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 2021-08-22
    • 2011-12-14
    • 1970-01-01
    相关资源
    最近更新 更多