Callback after the style has been rendered

╄→гoц情女王★ 提交于 2021-02-08 06:33:18

问题


All non-transition styles should be applied and rendered before applying transition styles. That's why such callback should exist.

demo

<button class="toggle">toggle</button>
<div class="overlay"></div>

.overlay {
  width      : 400px;
  height     : 400px;
  background : gray;

  display    : none;
  opacity    : 0;
  transition : opacity 0.3s ease-in-out;
}
.overlay.visible {
  opacity : 1;
}

var overlay = $(".overlay");
$(".toggle").click(function() {
  if (overlay.hasClass("visible")) {
    overlay.removeClass("visible").one("transitionend", function () {
      overlay.css("display", "none");
    });
  } else {
    overlay.css("display", "block");
    setTimeout(function () {
      overlay.addClass("visible");
    }, 0);
  }
});

You can see that gray block fades smoothly in chrome, but it jumps in firefox.

setTimeout(function () {
}, 0);

Zero timeout is not enough for firefox. I've checked that at my machine 5 miliseconds works fine 50/50.

Should I contact the fathers of this pain or there are any solutions?


回答1:


Yes, on firefox and IE you need to use getComputedStyle additionaly

var el = overlay[0];
el.style.display = 'block';

// force reflow
getComputedStyle(el).width;

setTimeout(function() {
    overlay.addClass("visible");
}, 0);


来源:https://stackoverflow.com/questions/19895932/callback-after-the-style-has-been-rendered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!