简体   繁体   English

使用过渡和JavaScript订购CSS样式

[英]Order CSS Styles with Transitions and JavaScript

if i apply a style to an element and immdiatily afterwards add css transition styles, the transition is applied to the style preceeding. 如果我将样式应用于元素,然后立即添加css过渡样式,则过渡将应用于之前的样式。 this might not always be the intention. 这可能并不总是目的。

i found a solution by using settimeout (0), is there any cleaner/more correct approach known ? 我通过使用settimeout(0)找到了解决方案,是否有已知的更清洁/更正确的方法?

http://jsfiddle.net/nicib83/XP9E7/ 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. 我并不是说如何最好地设置css样式,而是当应该应用第一种样式时应依次设置样式,而那时第二种样式不能被激活,但仅在此之后,我想在之后添加过渡。 settimeout fixes it, best solution ? settimeout修复它,最好的解决方案?

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");

You could take a page from the book of Twitter Bootstrap: 您可以从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: 然后以编程方式添加.in类,以使其淡入:

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

with your original div looking something like: 您原始的div看起来像:

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

I've been running up against this myself and also found the setTimeout solution. 我自己一直对此提出质疑,还找到了setTimeout解决方案。 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). JavaScript在与处理UI和DOM的线程分开的线程中运行(这就是为什么发生UI阻塞的原因)。

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. 在这种情况下,这两个JavaScript语句都会在文档注册第一次更改之前运行,并且最终会同时应用两个类。 setTimeout(fn,0) effectively makes the function asynchronous and shunts the functions to run at the next available opportunity. setTimeout(fn,0)有效地使函数异步,并分流在下一个可用时机运行的函数。 This allows the UI thread to catch up before the next class is added. 这允许UI线程在添加下一个类之前赶上来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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