HTML页面看起来像是在javascript运行后加载的.为什么h1的初始HTML具有颜色=橙色的样式,但在加载过程中从



我希望下面的代码加载一个显示"橙色"的页面,并在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>

这里不需要自定义等待函数对于这种情况,有一个名为setTimeout的内置方法,它是一个web浏览器API,它设置一个计时器,并在计时器用完后执行其中的一个函数

所以你的最终代码应该是这样的:

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>

最新更新