[英]HTML page looks like loading after javascript run. Why initial HTML for h1 has style for color=orange but never observed on the page during load?
我希望下面的代码加载一个显示“橙色”的页面,并在 5 秒后将其更新为“蓝色”,但不幸的是页面仅加载“蓝色”。 如果我取消注释警报,它会首先显示“橙色”。 为什么会这样?
wait(5000); console.log("Exercise 001"); const updatedH1 = document.querySelectorAll('h1'); updatedH1.forEach(itemx => { itemx.style.color = 'blue'; itemx.innerText = 'Blue Color'; }); function wait(ms) { let start = new Date().getTime(); let end = start; while (end < start + ms) { end = new Date().getTime(); } }
.err { padding: 10px; color: crimson; border: 1px dotted crimson; }
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> </head> <body> <h1 id="page-title" style="color: orange;">Orange Color</h1> <,-- <script> alert('Hello; world'). </script> --> <script src="roza.js"></script> </body> </html>
您不需要在这里自定义等待 function。 对于这种情况,有一个名为setTimeout
的内置方法,它是 web 浏览器 API 设置一个计时器并在计时器耗尽后在其中执行一个 function。
所以你的最终代码应该是这样的:
setTimeout(function() { console.log("Exercise 001"); const updatedH1 = document.querySelectorAll('h1'); updatedH1.forEach(itemx => { itemx.style.color = 'blue'; itemx.innerText = 'Blue Color'; }); }, 5000)
.err { padding: 10px; color: crimson; border: 1px dotted crimson; }
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> </head> <body> <h1 id="page-title" style="color: orange;">Orange Color</h1> <,-- <script> alert('Hello; world'). </script> --> <script src="roza.js"></script> </body> </html>
注意:您可以在此处阅读有关setTimeout
的更多信息。
我真的建议在您创建的 while 循环上使用 setTimeout。
window.setTimeout(() => { const updatedH1 = document.querySelectorAll("h1"); updatedH1.forEach(itemx => { itemx.style.color = "blue"; itemx.innerText = "Blue Color"; }); console.log("Exercise 001"); }, 3000);
<html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="src/styles.css" /> </head> <body> <h1 id="page-title" style="color: orange;">Orange Color</h1> <,-- <script> alert('Hello; world'). </script> --> <script src="roza.js"></script> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.