非常简单的JavaScript / jQuery示例:意外的评估顺序的指令 [英] very simple JavaScript / jQuery example: unexpected evaluation order of instructions

查看:115
本文介绍了非常简单的JavaScript / jQuery示例:意外的评估顺序的指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我感到惊讶的是,通过jQuery 之后应用CSS3过渡规则,基于jQuery的CSS属性更改实际上动画了此属性更改。请查看 http://jsfiddle.net/zwatf/3/

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/ :

最初,一个div由两个类定义,并且由于这两个类的默认CSS属性而具有一定的高度(200px)。然后使用jQuery通过删除一个类来修改高度:

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

这会将高度从200px减少到15px。

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

发生的事情是,高度的减少变成动画(至少在Firefox和Chrome上) 。在我的世界,如果指令的顺序有任何意义,这不应该发生。

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.

我想这个行为可以很好地解释。为什么会发生?如何预防?

这是我想要达到的:


  1. 使用jQuery修改默认样式

  2. 使用jQuery应用转换规则

  3. 使用jQuery更改属性(CSS3转换动画)

(1)和(2)应尽快发生,因此我不喜欢使用任何延迟。

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

推荐答案

运行脚本时,浏览器通常会将DOM更改推迟到结束,你可以通过读/写某些属性来强制重排:

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

或者你可以使用 setTimeout 同样的事情,让浏览器自动回流,然后添加类。

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.

这篇关于非常简单的JavaScript / jQuery示例:意外的评估顺序的指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆