为什么在背景更改之前会出现警报?

编程入门 行业动态 更新时间:2024-10-10 06:13:53
本文介绍了为什么在背景更改之前会出现警报?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以,我最近一直在尝试一些东西,并在脚本中获得了这段代码:

So, I've been trying stuff lately and got this piece of code in my script:

document.body.bgColor = "red"; alert("hello");

但是在Chrome浏览器中,警报对话框会首先弹出,并且只有在我关闭它之后,我的身体背景才会改变.在Firefox中,我得到了预期的行为,将主体背景更改为红色,然后弹出窗口.

But in Chrome, the alert dialog pops up first and only after I close it does the background of my body changes. In Firefox, I get the expected behaviour with body background changing to red followed by the popup.

我知道我们不应该依赖警报和类似的浏览器控件,但是谁能告诉我这是由于行为不在标准范围内还是因为我对上述代码的同步执行的理解是错误的? /p>

I know we shouldn't rely on alerts and similar browser controls but can anyone tell me if this is happening because the behaviour is not in the standards or if it's because my understanding of synchronous execution of the above code is wrong?

推荐答案

渲染过程具有其自己的生命周期,并且不会阻止javascript线程.他们俩都独立工作.

The rendering process has a lifecycle of it's own and does not block the javascript thread. They both work independently.

解决方案是暂停" JavaScript执行,以使渲染线程赶上来.这可以通过将简单的setTimeout设置为0

The solution is to "pause" the JavaScript execution to let the rendering threads catch up. This can be done via a simple setTimeout set to 0

document.body.style.backgroundColor = "red"; setTimeout(function() { alert("hey"); }, 0)

请注意,bgColor自2003年以来已被弃用,其中 DOM 2级规范.当前设置元素背景颜色的方法是通过element.style.backgroundColor.

Note that bgColor has been deprecated since 2003 with the DOM Level 2 Spec. The current way to set the background color of an element is via element.style.backgroundColor.

更多推荐

为什么在背景更改之前会出现警报?

本文发布于:2023-11-27 23:58:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640134.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:警报   背景

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!