如何检测伪元素上的animationend事件?

6

我知道如何检测普通DOM元素的animationend事件,但如何在伪元素上实现呢?

我知道要使用animationend事件,但如何使用它来附加伪元素并处理程序?

我尝试过以下方法,但好像行不通。

document.querySelector("#someSelector:after").addEventListener("animationend",...,false)

我该如何使用原生JavaScript实现这个功能?
1个回答

3
:after 伪元素不能像 DOM 中的一部分那样被选择,因为它们不是 DOM 的一部分。尽管如此,在“父级”上触发事件仍然是可能的,因为它们会在 :after 的“父级”上触发。例如,如果您将 :after 应用于带有 id'containybox' 的 DOM 元素上,则可以获取该 DOM 元素并在其 animationend 上触发。当 :after 的动画结束时,事件将触发。
var containerBox = document.getElementById('containybox');    

containerBox.addEventListener('animationend', function() {
  console.log("Animation ended!");
});

完整可工作的代码片段:

var containerBox = document.getElementById('containybox');

containerBox.addEventListener('animationend', function() {
  console.log("Animation ended!");
});

containerBox.addEventListener('transitionend', function() {
  console.log("Transition ended!");
});
#containybox {
  position: relative;
  width: 100px;
  height: 100px;
  background: #fadebc;
  padding: 10px;
  text-align: center;
}
#containybox:after {
  content: "Standard aftermibob.";
  display: block;
  position: fixed;
  left: 120px;
  width: 100px;
  height: 100px;
  background: #bcdefa;
  animation: animatedBackground 1000ms linear;
}
#containybox:hover:after {
  background: #bcfade;
  transition: background-color 1000ms linear;
}
@keyframes animatedBackground {
  from {
    background-color: #000000;
  }
  to {
    background-color: #bcdefa;
  }
}
<div id="containybox">
  Just a standard containybox.
</div>


2
甚至可以通过AnimationEvent.pseudoElement属性区分所动画的内容,该属性值为空字符串或者是"::after" / "::before"。AnimationEvent对象将作为第一个参数传递到您的事件监听器中。 - myf
1
糟糕,Chrome中的AnimationEvent缺少pseudoElement属性(bug https://bugs.chromium.org/p/chromium/issues/detail?id=437132)。在Chrome和Firefox中的`TranstitionEvent`中都存在该属性。 - myf

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