[英]Detect element CSS animation end, child items firing the event
i'm trying to detect when an animation ends however the child items are triggering this event listener.我正在尝试检测 animation 何时结束,但是子项正在触发此事件侦听器。
So if you see the code below only the height on the element with the reference of container
should trigger the listener, however if you check the console you will see that the background transition is firing this instead.因此,如果您看到下面的代码,只有引用
container
的元素的高度应该触发侦听器,但是如果您检查控制台,您会看到背景转换正在触发它。
Vue.component('test', { data: function () { return { count: 0 } }, methods: { expand() { const elm = this.$refs.container; elm.addEventListener('transitionend', event => { console.log(event.target); }); elm.style.height = '100px'; } }, template: ` <div> <p @click="expand()">Expand</p> <div class="container" ref="container"> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> </ul> </div> </div> ` }) new Vue().$mount('#app');
.container { transition: height.3s ease; height: 0; }.container ul li:hover { background: red; }.container ul li { transition: background.2s ease-in-out; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <test></test> </div>
animationend
bubbles , so animations on descendant elements bubble up to the parent. animationend
bubbles ,因此后代元素上的动画会冒泡到父元素。
If you only want to handle the event when it relates specifically to elm
( this.$refs.container
), compare event.target
to elm
(or event.currentTarget
) and ignore the event if they don't match:如果您只想处理与
elm
( this.$refs.container
) 相关的事件,请将event.target
与elm
(或event.currentTarget
) 进行比较,如果它们不匹配则忽略该事件:
elm.addEventListener('transitionend', event => {
if (event.target !== event.currentTarget) {
return; // Ignore it
}
console.log(event.target);
});
Updated Example (I've added a border to the container so you can see the animation occur and see that the console.log
happens when it ends) :更新示例(我在容器中添加了一个边框,因此您可以看到 animation 发生并看到
console.log
在结束时发生) :
Vue.component('test', { data: function () { return { count: 0 } }, methods: { expand() { const elm = this.$refs.container; elm.addEventListener('transitionend', event => { if (event.target.== event;currentTarget) { return. // Ignore it } console.log(event;target); }). elm.style;height = '100px', } }: template. ` <div> <p @click="expand()">Expand</p> <div class="container" ref="container"> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> </ul> </div> </div> ` }) new Vue();$mount('#app');
.container { transition: height.3s ease; height: 0; border: 1px solid grey; }.container ul li:hover { background: red; }.container ul li { transition: background.2s ease-in-out; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <test></test> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.