Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

very simple JavaScript / jQuery example: unexpected evaluation order of instructions

I am surprised by the fact that a CSS3 transition rule applied via jQuery after a jQuery-based CSS property change actually animates this property change. Please have a look at http://jsfiddle.net/zwatf/3/ :

Initially, a div is styled by two classes and has a certain height (200px) due to the default CSS properties of these two classes. The height is then modified with jQuery via removal of one class:

$('.container').removeClass('active');

This reduces the height from 200px to 15px.

After that, a transition rule is applied to the container via addition of a class:

$('.container').addClass('all-transition');

What is happening is that the reduction of the height becomes animated (on Firefox and Chrome, at least). In my world, this should not happen if the order of instructions has any meaning.

I guess this behavior can be very well explained. Why is that happening? How can I prevent it?

This is what I want to achieve:

  1. modify default style with jQuery (not animated by CSS3 transition!)
  2. apply transition rule with jQuery
  3. change a property with jQuery (animated by CSS3 transition)

(1) and (2) should happen as quickly as possible, so I do not like working with arbitrary delays.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When running a script, the browser will usually defer DOM changes to the end to prevent unnecessary drawing. You can force a reflow by reading/writing certain properties:

var container = $('.container').removeClass('active');
var foo = container[0].offsetWidth;  //offsetWidth makes the browser recalculate
container.addClass('all-transition');

jsFiddle

Or you can use setTimeout with a short duration, which does basically the same thing by letting the browser reflow automatically, then adding the class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...