首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不带setTimeout的vue点击动画

不带setTimeout的vue点击动画
EN

Stack Overflow用户
提问于 2018-02-07 06:21:41
回答 2查看 7K关注 0票数 3

我想要一个div闪光的情况下,用户点击它。是否有无需手动运行setTimeout的解决方案?

使用setTimeout的解决方案:

app.html

代码语言:javascript
复制
<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

代码语言:javascript
复制
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/

EN

回答 2

Stack Overflow用户

发布于 2018-07-06 22:29:25

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

代码语言:javascript
复制
var demo = new Vue({
  el: '#demo',
  data: {
    animated: false
  },
  methods: {
    animate() {
      this.animated = true
    }
  }
})
代码语言:javascript
复制
<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

票数 14
EN

Stack Overflow用户

发布于 2018-02-08 02:44:38

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

app.html

代码语言:javascript
复制
<div id="app" v-on:click="toggleClass('app', 'flashing')">flash when clicked</div>

app.css

代码语言:javascript
复制
.flashing {
  animation: flash .5s;
}

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

app.js

代码语言:javascript
复制
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的更多信息。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48652941

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档