为什么我的JavaScript代码不能从上到下编码? [英] Why my javascript code not process from top to bottom coding?

查看:73
本文介绍了为什么我的JavaScript代码不能从上到下编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我的javascript代码不能自上而下编码?

https://jsfiddle.net/p47f6Lcy/1/



使用我的代码当按 id =测试为什么在更改之前为 alert backgroundColor translate3d



查看我的代码,它应该更改 backgroundColor translate3d 在调用函数之前 test2_fn



如何更改 backgroundColor translate3d befire alert



..

 < div id =testonclick =test_fn()> 
CLICK
< / div>

< script>
function test_fn(){
document.getElementById(test)。style.backgroundColor =red;
document.getElementById(test)。style.transform =translate3d(500px,0px,0px);
test2_fn();


function test2_fn(){
alert(555);
}
< / script>


解决方案

nnnnnn 在评论中提到: b
$ b


因为浏览器不重画直到当前的JS完成执行。所以元素样式已经在DOM中更新了,你现在还没有看到。


如果你真的想这样做,您可以将其他函数的执行推迟到事件循环中的下一个循环。您可以简单地使用 setTimeout(test2_fn,0)



工作小提琴



这也是一个很好的阅读。


Why my javascript code not process from top to bottom coding ?

https://jsfiddle.net/p47f6Lcy/1/

With my code when press on id="test" Why still alert before change backgroundColor and translate3d

See on my code it's should change backgroundColor and translate3d before call function test2_fn

How can i do for change backgroundColor and translate3d befire alert ?

..

<div id="test" onclick="test_fn()">
CLICK
</div>

<script>
function test_fn(){
    document.getElementById("test").style.backgroundColor = "red";
    document.getElementById("test").style.transform = "translate3d(500px, 0px, 0px)";    
    test2_fn();
}

function test2_fn(){
    alert("555");
}
</script>

解决方案

As nnnnnn mentioned in the comments:

Because the browser doesn't repaint the screen until the current JS finishes executing. So the element styles have been updated in the DOM, you just don't see it yet.

If you really want to do it, you can postpone the execution of the other function to the next cycle in the event loop. You can simply use setTimeout(test2_fn, 0).

Working fiddle

This is also a good read.

这篇关于为什么我的JavaScript代码不能从上到下编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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