动画结束事件是否也会在子元素动画结束时触发?

4
我有一个带有动画的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>


我很好奇,如果你在class outer上使用#id,那么是否会排除子元素.inner? - zipzit
@zipzit 刚刚添加了一个使用id的代码片段。问题仍然存在。 - Boris Grunwald
1个回答

3

您可以检查事件的目标是否为侦听器所附加到的元素。当子元素上的动画结束时,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>


这个有效。但是调用 e.stopPropagation() 不会阻止冒泡吗? - Boris Grunwald
但是为什么不呢? - Boris Grunwald
@BorisGrunwald 这确实可以阻止冒泡:https://jsfiddle.net/0trxeL65/ - Unmitigated

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接