我希望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/
最佳答案
与Christopher's answer相似,但在某种程度上对Vue来说是惯用的。这使用通过绑定(bind)类和animationend
事件应用的CSS动画。
var demo = new Vue({
el: '#demo',
data: {
animated: false
},
methods: {
animate() {
this.animated = true
}
}
})
<link href="https://unpkg.com/[email protected]/animate.min.css" rel="stylesheet" />
<script src="https://unpkg.com/[email protected]/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。