运行 仅在所有转换结束后的代码

Run code only after all transitions have ended

对我来说这是一个脑洞大开

这个事件会在每次转换结束时触发,在我们的例子中5次因为backgroundColor, borderTopLeftRadius, borderTopRightRadius... 我不想要,我希望只有在所有转换结束后才触发此事件。这是一个片段:

function changeStyle() {
  const elem = document.getElementById("elem");
  const logs = document.getElementById("logs");
  elem.style.backgroundColor = "red";
  elem.style.borderRadius = "30px";

  elem.ontransitionend = () => {
    logs.insertAdjacentText("beforeend", "transition ended");
  }
}
#elem {
  height: 100px;
  width: 100px;
  color: white;
  background-color: blue;
  transition: background-color 0.5s, border-radius 0.6s;
}
<div onclick="changeStyle()" id="elem">
  click me !
</div>

<span id="logs"></span>

transitionend 事件包含一个 propertyName 属性,它指的是结束的 属性 转换。在这里,您可以检查事件以检查是哪个 属性 导致事件触发。由于最长的过渡是边界半径,因此检查 propertyName 是否是边界半径之一:

function changeStyle() {
  const elem = document.getElementById("elem");
  const logs = document.getElementById("logs");
  elem.style.backgroundColor = "red";
  elem.style.borderRadius = "30px";

  elem.ontransitionend = (e) => {
    if (e.propertyName === "border-bottom-right-radius") {
      logs.insertAdjacentText("beforeend", "transition ended");
    }
  }
}
#elem {
  height: 100px;
  width: 100px;
  color: white;
  background-color: blue;
  transition: background-color 0.5s, border-radius 0.6s;
}
<div onclick="changeStyle()" id="elem">
  click me !
</div>

<span id="logs"></span>