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

橙三吉。 提交于 2019-11-28 13:31:46

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.

Why is that happening?

I guess because the DOM sees them applied together; immediate consecutive actions are usually cached instead of being applied one after the other.

How can I prevent it?

A (very small) timeout should do it: http://jsfiddle.net/zwatf/4/

(from the comments) Manually triggering a reflow also helps: http://jsfiddle.net/zwatf/9/

I do not like working with arbitrary delays.

Then I think the only other possible way is to remove the height from the animated css properties, i.e. you need to explicitly state which ones you wanted to animate: http://jsfiddle.net/zwatf/5/

i think, it just happens too fast. if you do this:

$('.container').toggleClass('active',function() {
    $('.container').addClass('all-transition');
});

it will behave as you expected, right?

ok, fine, i tested it, but I didn't realize it didn't work as expected. Here an alternative to make it up:

$('.container').removeClass('active').promise().done(function(){
    $('.container').addClass('all-transition');

    $('.container').css('height','300'); //to see the easing
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!