问题
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