【问题标题】:vue click animation without setTimeout没有setTimeout的vue点击动画
【发布时间】:2018-02-06 22:21:41
【问题描述】:

我希望 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 小提琴:https://jsfiddle.net/ang3ukg2/

【问题讨论】:

  • 您想在何时/何地设置时间?
  • 为什么不用css :active
  • 也许您可以使用 mousedown 和 mouseup 事件而不是 click 事件,然后从 css 转换中受益?

标签: javascript animation vue.js timeout


【解决方案1】:

类似于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

【讨论】:

  • 这应该是公认的答案,因为它解决了在动画结束时删除类的问题。
【解决方案2】:

另一种方法是使用 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的信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 2012-07-10
    • 1970-01-01
    相关资源
    最近更新 更多