首页 > 解决方案 > VueJS - 在显示元素之前旋转

问题描述

我试图在不同的方向显示一条线。垂直和水平方向都按预期工作。但是对于对角线方向,我需要在显示之前先旋转它。问题是它垂直显示线条然后旋转到 135 度。我知道元素需要在旋转之前显示。那么我怎样才能使这项工作呢?

这是一个工作演示

HTML

<div id="app">
  <button @click="toggle">Toggle</button>
  <span>Direction: {{ direction }}</span>
  <transition name="line-transition">
    <div v-if="direction"
       class="line"
      :class="direction">
    </div>
  </transition>
</div>

VueJS

new Vue({
  el: "#app",
  data: {
    direction: null
  },
  methods: {
    toggle: function(){
      const arr = [ 'vertical', 'horizontal', 'diagonal']

      /* random select */
      this.direction = arr[Math.floor(Math.random() * arr.length)]

      /* hide line before toggling direction */
      setTimeout(() => {
            this.direction = null
      }, 1000)
    }
  }
})

CSS:

.line.vertical {
  width: 10px;
  height: 100px;
}
.line.horizontal {
  width: 100px;
  height: 10px;
}
.line.diagonal {
  transform: rotate(135deg);
  width: 10px;
  height: 100px;
}

.line-transition-enter-active,
.line-transition-leave-active {
  animation: slidein 1s;
}

@keyframes slidein {
  from {
    transform: scaleX(0) scaleY(0);
  }
   to {
    transform: scaleX(1) scaleY(1);
  }
}

标签: css

解决方案


想法是使用伪元素来创建对角线,这样您就可以避免在动画元素上使用 transform 之间的冲突:

.line.diagonal {
  width:100px;
  height:100px;
  background:transparent;
}
.line.diagonal:before {
  content:"";
  top:0;
  left: calc(50% - 5px);
  position:absolute;
  transform: rotate(135deg);
  border-radius: inherit;
  background: blue;
  width: 10px;
  height: 100px;
}

完整代码:

https://jsfiddle.net/m4g198r2/28/


推荐阅读