【问题标题】:Waiting for DOM manipulation to finish before triggering CSS transition?在触发 CSS 转换之前等待 DOM 操作完成?
【发布时间】:2021-05-17 16:15:29
【问题描述】:

我想:

  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 毫秒)

【问题讨论】:

标签: javascript css dom css-transitions


【解决方案1】:

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

transitionend 事件在 CSS 转换完成时触发。如果在完成之前移除了转换,例如移除了转换属性或将显示设置为无,则不会生成事件。

可能的代码更新

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>

【讨论】:

    猜你喜欢
    • 2021-11-26
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    相关资源
    最近更新 更多