过渡开始得太早,而css样式尚未完全应用

时间:2012-06-06 12:03:06

标签: javascript css google-chrome webkit-transition

我的代码是here。 有三个位置:zero(0,0)end(200,200)random(0,200)

div位于开头的random(0,200)位置。

我想:

步骤1)将div设置在zero(0,0)位置。这一步没有动画

步骤2)通过转换将其从位置zero移动到位置end。这一步有动画

这样的代码效果不好:

document.getElementById('x').className = 'pos_zero';    // set the div to the position zero(0,0)
move(); 
// in function move: 
// document.getElementById('x').className = ' trans'; 
// document.getElementById('x').className += ' pos_end' ;

似乎过渡开始得太早,而css样式(className = 'pos_zero')尚未完全应用。它只是从位置random直接移动到位置end。而我真正想要的是动画从位置end定位zero,而不是random

这样的代码有效:

document.getElementById('x').className = 'pos_zero';    // set the div to the position zero(0,0)    
setTimeout('move()',1);

此代码使用timeout函数成功完成。此代码首先将div设置在位置pos_zero中,然后通过timeout函数异步转换。 timeout函数似乎不太专业。

所以,我正在寻找更专业的解决方案。

顺便说一下。我想知道。如果有任何方法可以确保完全应用样式,比如“Style.flush()”或其他什么?

@Inerdial它确实有用!非常感谢。要强制更新(强制立即,同步重排或重新布局),您的javascript应该读取受更改影响的属性,例如someSpan和otherSpan的位置。`新代码没有超时工作。

document.getElementById('x').className = 'pos_zero';
var tmp = document.getElementById('x').offsetTop; // read a property to force an update.
move(); 

谢谢大家。对不起我的困惑。

2 个答案:

答案 0 :(得分:2)

感谢@Inerdial。它确实有效! 实际上这个答案来自他的评论。

要强制进行更新(强制立即进行同步重排或重新布局),您的javascript应该读取受更改影响的属性,例如: someSpan和otherSpan的位置。` - stackoverflow.com/a/1397505/41655

新代码无法超时(jsfiddle.net/vd6V8):

document.getElementById('x').className = 'pos_zero';
var tmp = document.getElementById('x').offsetTop; // read a property to force an update.
move(); 

谢谢大家。对不起我的困惑。

答案 1 :(得分:0)

这实际上是唯一的方法,因为在CSS更改之间,浏览器需要“脱离”当前正在运行的代码。

当您使用setTimeout()代码退出时,将应用CSS,然后运行其他代码。这会产生预期的行为。