CSS转换获胜't在没有“setTimeout”的情况下运行

CSS transition won't run without `setTimeout`

本文关键字:setTimeout 运行 情况下 获胜 转换 CSS      更新时间:2023-09-26

我使用JS将元素的不透明度设置为0,然后设置不透明度转换,最后将不透明度设置成1。我希望看到元素立即消失,然后又消失。相反,什么都没发生。

但是,如果在设置转换并将不透明度设置为1之前添加setTimeout,则转换确实会触发。这里发生了什么?浏览器是否正在批处理CSS更改?有比setTimeout破解更好的方法吗?

https://jsfiddle.net/Lpk5en54/2/

<span>abeclc</span>
<button>Go</button>
var span = document.getElementsByTagName("span")[0];
document.getElementsByTagName("button")[0].onclick = function () {
    span.style.transition = '';
    span.style.opacity = '0';
    //setTimeout(function () {
        span.style.transition = 'opacity 2s';
        span.style.opacity = '1';
    //}, 100);
};

您需要触发回流:https://jsfiddle.net/Lpk5en54/3/

var span = document.getElementsByTagName("span")[0];
document.getElementsByTagName("button")[0].onclick = function () {
    span.style.transition = '';
    span.style.opacity = '0';
 //   setTimeout(function () {
    var foo = span.offsetTop
        span.style.transition = 'opacity 2s';
        span.style.opacity = '1';
  //  }, 100);
};