如何使伪类回流?

问题描述

我有这个旋转木马,里面有带动画的孩子。每次更改幻灯片时,我都希望动画重新启动/重排。问题是动画应用于 :before 伪类。我搜索了导致元素回流的问题,我想出了类似的东西:

const reset_animation = (el) => {
    el.style.animation = "none";
    el.offsetHeight; /* trigger reflow */
    el.style.animation = null;
 }

document.querySelectorAll(`.${carouselItem[i]}`).forEach((el) => {
    reset_animation(el)
})

但它不影响伪类。我还尝试使用 window.getComputedStyle 获取伪类,但我无法设置属性,因为所有属性都是只读的。

解决方法

让 JS 更新伪元素样式的一种方法是使用 CSS 变量设置该样式。

例如:

.withafter {
  --name: expand; /* the name of the animation for the after pseudo element */
  width: 20vmin;
  height: 20vmin;
  background-color: cyan;
  position: relative;
}
.withafter::after {
  content: '';
  background-color: red;
  position: absolute;
  width: 10vmin;
  height: 10vmin;
  animation: var(--name) 10s linear;
}
@keyframes expand {
  to {
   transform: scale(2);
  }
}
<div class="withafter"></div>

然后,当您想将其设置为 none 时,请使用 el.style.setProperty('--name','none') 在实际元素上设置 CSS 属性,而不是设置 el 的动画名称。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...