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

标签 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 步)通过转换将其从位置 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/

相关文章:

javascript - 如何在异步函数中测试 jest.fn().mock.calls

javascript - AngularJS 的预检选项请求不适用于 Chrome?

google-chrome - bat文件开始打开chrome chrome ://downloads/

html - 如何在多个 div 中重用 angularjs 条形图指令

javascript - Bootstrap 主题的模块化和可采纳性

css - Bootstrap 3 流体网格布局问题?

google-chrome - 在Chrome中, "too many"有多少个重定向?

javascript - 未定义下划线模板 Uncaught ReferenceError 变量

javascript - 如何对不同 parent 的多个 child 使用 jquery 切换?

javascript - 如何根据字符数显示/隐藏 div?