【问题标题】:animationend event also also fires on end of animations of child elements?animationend 事件也会在子元素的动画结束时触发?
【发布时间】:2021-07-09 04:13:16
【问题描述】:

我有一个带有动画的 div。

我已经为这个 div 附加了一个 animationend 事件监听器。

这个 div 还有一个带有动画的子元素。

由于某种原因,当子元素的动画结束时,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>

【问题讨论】:

  • 我很好奇,如果你在类外部使用#id,会排除子 .inner 元素吗?
  • @zipzit 刚刚添加了一个使用 id 的 sn-p。还是一样的问题

标签: javascript html css


【解决方案1】:

您可以检查事件的目标是否是侦听器附加到的元素。当子元素上的动画因为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() 不会阻止冒泡吗?
  • 但为什么没有*
  • @BorisGrunwald 它确实可以防止冒泡:jsfiddle.net/0trxeL65
猜你喜欢
  • 2019-08-11
  • 1970-01-01
  • 2012-02-29
  • 2014-08-10
  • 2013-08-07
  • 2015-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多