在触发 CSS 转换之前等待 DOM 操作完成?

Waiting for DOM manipulation to finish before triggering CSS transition?

我愿意:

  1. 通过首先修改 DOM(状态之前)来准备 CSS 转换,例如 el.style.width = "200px"
  2. 通过再次修改 DOM(状态之后)触发 CSS 转换,例如 el.style.width = "0px"

我看到的问题是您需要等待第一个 DOM 操作(第 1 步)完成,然后才能继续触发 CSS 转换(第 2 步)。

我找到的解决方法是在两者之间等待 100 毫秒。似乎适用于大多数浏览器,但如果您实际上可以等待 DOM 操作完成后再继续,那就太好了。

function dostuff() {

    let el = document.getElementById("widget");
    
    // before state (beginning of transition)
    // big box in lower right corner
    el.style.top = "100px"
        el.style.left = "100px"
        el.style.width = "200px"
        el.style.height = "200px"

        setTimeout(() => {
        // after stated (end of transiton)
      // small box in upper left corner
            el.style.top = "0px"
            el.style.left = "0px"
            el.style.width = "10px"
            el.style.height = "10px"
        }, 100);
  
}
#widget {
  position: absolute;
  left: 0px;
  top: 0px;
  height: 0px;
  width: 0px;
  border: 3px solid red;
  transition: all 0.2s;
}
<button type="button" onClick="dostuff()">Click Me!</button>

<div id="widget">
</div>

JSFiddle 示例 https://jsfiddle.net/fm59n02u/(适用于 100 毫秒,不适用于 10 毫秒)

看看:https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/transitionend_event

The transitionend event is fired when a CSS transition has completed. In the case where a transition is removed before completion, such as if the transition-property is removed or display is set to none, then the event will not be generated.

可能的代码更新

function dostuff() {

  let el = document.getElementById("widget");

  // before state (beginning of transition)
  // big box in lower right corner
  el.style.top = "100px"
  el.style.left = "100px"
  el.style.width = "200px"
  el.style.height = "200px"

  el.addEventListener('transitionend', () => {
    el.style.top = "0px"
    el.style.left = "0px"
    el.style.width = "10px"
    el.style.height = "10px"
  });
}
#widget {
  position: absolute;
  left: 0px;
  top: 0px;
  height: 0px;
  width: 0px;
  border: 3px solid red;
  transition: all 0.2s;
}
<button type="button" onClick="dostuff()">Click Me!</button>

<div id="widget">
</div>