没有setTimeout的vue点击动画

时间:2018-02-06 22:21:41

标签: javascript animation vue.js timeout

我想要一个div来闪存,以防用户点击它。有没有手动运行setTimeout的解决方案?

使用setTimeout解决方案:

app.html

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>

<style>
div { transition: background-color 1s; }
div.flashing { background-color: green; transition: none; }
</style>

<div id="app" :class="{'flashing':flashing}" v-on:click="flash">flash when clicked</div>

app.js

const data = { flashing: false }

new Vue({
  el: '#app',
  data,
  methods: { flash }
})

function flash() {
  data.flashing = true;
  setTimeout(() => data.flashing = false, 100);
}

Js Fiddle:https://jsfiddle.net/ang3ukg2/

2 个答案:

答案 0 :(得分:5)

类似于Christopher's answer,但在某种程度上更类似于Vue。这将使用通过绑定类和animationend事件应用的CSS动画。

var demo = new Vue({
  el: '#demo',
  data: {
    animated: false
  },
  methods: {
    animate() {
      this.animated = true
    }
  }
})
<link href="https://unpkg.com/animate.css@3.5.2/animate.min.css" rel="stylesheet" />
<script src="https://unpkg.com/vue@2.2.4/dist/vue.min.js"></script>
<div id="demo">
  <h1 :class="{'bounce animated': animated}" @animationend="animated = false">
    Animate Test
  </h1>
  <button @click="animate">
    Animate
  </button>
</div>

全部归功于Robert Kirsz who proposed the solution in a comment to another question

答案 1 :(得分:0)

另一种方法是使用CSS动画并挂钩animationend事件:

app.html     

<div id="app" v-on:click="toggleClass('app', 'flashing')">flash when clicked</div>

app.css

.flashing {
  animation: flash .5s;
}

@keyframes flash {
  0% {
    background-color: none;
  }
  50% {
    background-color: green;
  }
  100% {
    background-color: none;
  }
}

app.js

new Vue({
  el: '#app',

  methods: {
    toggleClass (id, className) {
        const el = document.getElementById(id)
        el.classList.toggle(className)
    }
  },

  mounted () {
    document.getElementById('app').addEventListener('animationend', e => {
        this.toggleClass(e.target.id, 'flashing')
    })
  }
})

工作示例:https://jsfiddle.net/Powercube/ang3ukg2/5/

这将允许您为其他类重用toggleClass方法,而不会使用任意类数据和超时混淆应用程序。

您可以找到有关animation events at the MDN

的更多信息