我的代码是here 。
共有三个位置:zero(0,0)
、end(200,200)
、random(0,200)
。
div 位于开头的 random(0,200)
位置。
我想要:
第 1 步)将 div 设置在位置 zero(0,0)
。这一步没有动画
第 2 步)通过转换将其从位置 0
移动到位置 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 style(className = 'pos_zero'
) 尚未完全应用。它只是直接从位置random
移动到位置end
。我真正想要的是从位置零
定位end
的动画,而不是从随机
定位。
这样的代码有效:
document.getElementById('x').className = 'pos_zero'; // set the div to the position zero(0,0)
setTimeout('move()',1);
此代码通过使用超时
函数成功完成。此代码首先将 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();
谢谢大家。对于我造成的困惑表示歉意。
最佳答案
感谢@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();
谢谢大家。对于我造成的困惑表示歉意。
关于javascript - 过渡开始得太早,而 css 样式尚未完全应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10913848/