我有一个带有动画的 div。
我已将animationend 事件侦听器附加到该div。
该 div 还有一个带有动画的子元素。
由于某种原因,当子元素的动画完成时,animationend 事件也会触发。
为什么是这样?有办法解决这个问题吗?我希望animationend 事件仅在我附加事件监听器的元素完成时运行。
document.querySelector('.outer').addEventListener('animationend',function () {
console.log('done')
})
body {
height:100vh;
display:grid;
place-items:center;
}
.outer {
display:grid;
place-items:center;
height:200px;
width:200px;
background:black;
animation:spin 2s
}
.inner {
height:50px;
width:50px;
background:red;
animation:spin 2s 2s
}
@keyframes spin {
from {
transform:rotate(0)
}
to {
transform:rotate(360deg)
}
}
<div class="outer">
<div class="inner">
</div>
</div>
尝试用 id 代替。还是没有运气
document.querySelector('#outer').addEventListener('animationend',function () {
console.log('done')
})
body {
height:100vh;
display:grid;
place-items:center;
}
#outer {
display:grid;
place-items:center;
height:200px;
width:200px;
background:black;
animation:spin 2s
}
.inner {
height:50px;
width:50px;
background:red;
animation:spin 2s 2s
}
@keyframes spin {
from {
transform:rotate(0)
}
to {
transform:rotate(360deg)
}
}
<div id="outer">
<div class="inner">
</div>
</div>
您可以检查事件的目标是否是侦听器附加到的元素。当子元素上的动画结束时也会调用事件处理程序,因为animationend
事件气泡。
document.querySelector('.outer').addEventListener('animationend', function(e) {
if(e.target === this) console.log('done')
})
document.querySelector('.outer').addEventListener('animationend',function (e) {
if(e.target === this) console.log('done')
})
body {
height:100vh;
display:grid;
place-items:center;
}
.outer {
display:grid;
place-items:center;
height:200px;
width:200px;
background:black;
animation:spin 2s
}
.inner {
height:50px;
width:50px;
background:red;
animation:spin 2s 2s
}
@keyframes spin {
from {
transform:rotate(0)
}
to {
transform:rotate(360deg)
}
}
<div class="outer">
<div class="inner">
</div>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)