Order CSS Styles with Transitions and JavaScript

自古美人都是妖i 提交于 2019-12-24 07:15:03

问题


if i apply a style to an element and immdiatily afterwards add css transition styles, the transition is applied to the style preceeding. this might not always be the intention.

i found a solution by using settimeout (0), is there any cleaner/more correct approach known ?

http://jsfiddle.net/nicib83/XP9E7/

$("div").css("opacity", 1);

$("div").css("-webkit-transition", "all 0.35s");

/* Works
window.setTimeout(function () {
    $("div").css("-webkit-transition", "all 0.35s");
}, 0);
*/

best regards

Edit:

i didn't mean how best to set css styling but how to sequentially set styles when the first style should be applied without the second being active at that time but only afterwards, i wan to add transition afterwards. settimeout fixes it, best solution ?


回答1:


It's much better to pre-define a class that contains both of the properties you want to apply, and add that class programmatically to the element. Both of the properties will be applied together.

.myClass {
    opacity: 1;
    -webkit-transition: all 0.35s;
}

$("div").addClass("myClass");



回答2:


You could take a page from the book of Twitter Bootstrap:

fade {
    opacity: 0;
    -webkit-transition: opacity 0.15s linear;
    -moz-transition:opacity 0.15s linear;
    -o-transition:opacity 0.15s linear;
    transition:opacity 0.15s linear;
}
.fade.in{
    opacity:1;
}

then programatically add the .in class when you want it to fade in:

$("div").addClass("in");

with your original div looking something like:

<div class="fade">Box</div>



回答3:


I've been running up against this myself and also found the setTimeout solution. After some research the issue is how the browser handles scheduling. The JavaScript runs in its own thread separate from the threads dealing with the UI and the DOM (which is why issues like UI blocking happen).

In cases like this both JavaScript statements run before the document registers the first change and it ends up applying both classes at the same time. setTimeout(fn,0) effectively makes the function asynchronous and shunts the functions to run at the next available opportunity. This allows the UI thread to catch up before the next class is added.



来源:https://stackoverflow.com/questions/14284897/order-css-styles-with-transitions-and-javascript

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