简体   繁体   中英

CSS transitions don't work unless I use timeout

I have a couple of classes: hide is display: none , and transparent is opacity: 0 . The element pr_container has -webkit-transition: opacity 1s . The following JQuery-based code makes an element appear in an animated fasion:

pr_container.removeClass("hide");
setTimeout(function() { pr_container.removeClass("transparent"); }, 0);

However, when I remove setTimeout and instead just remove the second class, there is no animation. Why?

Edit: I'm using the latest Chrome, I haven't checked other browsers yet.

Edit: I tried putting both calls in the same setTimeout callback - no animation. So it's clearly about separation.

Edit: here's the jsFiddle: http://jsfiddle.net/WfAVj/

You can't make a transition if you are changing display property at the same time. So in order to make it work you have to hide your element some other way. For example:

.hide {
    height: 0;
    width: 0;
    /* overflow: hidden; padding: 0; border: none; */
}

http://jsfiddle.net/dfsq/WfAVj/1/

There's no reasonable " curve " to transit from one display status to another, so in current implementation of browsers, any transition that somehow involves display will end up with no transition at all.

With this code:

pr_container.removeClass("hide");
pr_container.removeClass("transparent");

You can imagine the two statements execute in a single "blocking" queue, so browsers practically renders the element from class="hide transparent" to class="" , and as stated above, the hide class practically invalidates any existing transition.

By using

pr_container.removeClass("hide");
setTimeout(function() { pr_container.removeClass("transparent"); }, 0);

You told browsers to remove the "transparent" class "as soon as possible, but no in the same queue", so browser first removes "hide", and then moves on. The removal of "transparent" happens when the browser think it has resource to spare, thus the transition does not get invalidated.

only the "transperent" class produce animation .. "hide" is instant. So start the animation and if needed "hide" after 1 second:

 test.addClass("transparent");
 //hide after 1 sec, when the animation is done
 setTimeout(function() {test.addClass("hide"); }, 1000);  //1000ms = 1sec

http://jsfiddle.net/WfAVj/4/

By using suggestions in the linked question, I made a version that I'm satisfied with:

.test {
    -webkit-transition: visibility 1s, opacity 1s;
}

.hide {
    visibility: hidden;
}

.transparent {
    opacity: 0;
}

http://jsfiddle.net/xKgjS/

Edit: now the two classes can even be combined to one!

Thanks to everyone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM