希望你一切都好。我想知道你的集体天才是否可以帮助我?我有一个 div,它是一个圆圈。我还有三个 CSS 类。我想每 3 秒更改一次 div 的类和标签的文本。 任何能指出我哪里出错的人都会非常有帮助。
这是我所拥有的,目前似乎没有做任何事情:
function loadTraffLight() {
var traffLight = document.getElementById("traffLight");
var status = document.getElementById("status");
var timer;
var go = function traffGo() {
timer = setInterval(function() {
if (traffLight.class == "red") {
traffLight.className = "yellow";
status.innerText = "O.K";
} else if (traffLight.class == "yellow") {
traffLight.className = "green";
status.innerText = "Authorised";
} else {
traffLight.className = "red";
status.innerText = "Stop Working";
}
}, 3000);
};
}
#traffLight {
border-radius: 100px;
width: 200px;
height: 200px;
border: 1px solid #000000;
margin: 0 auto;
color: #808080;
}
#status {
text-align: center;
vertical-align: bottom;
}
.red {
background: #ff0000;
}
.yellow {
background: #ffd800;
}
.green {
background: #00ff21;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Traffic light</title>
</head>
<body onload="loadTraffLight()">
<h1>Traffic light effect demo</h1>
<div id="traffLight">
<label id="status"></label>
</div>
</body>
</html>
最佳答案
请始终使用className
。除此之外,我稍微改变了你的函数结构:
function loadTraffLight() {
var traffLight = document.getElementById("traffLight");
var status = document.getElementById("status");
var timer;
timer = setInterval(function () {
if (traffLight.className == "red") {
traffLight.className = "yellow";
status.innerText = "O.K";
}
else if (traffLight.className == "yellow") {
traffLight.className = "green";
status.innerText = "Authorised";
}
else {
traffLight.className = "red";
status.innerText = "Stop Working";
}
}, 1000);
}
#traffLight{
border-radius:100px;
width:200px;
height:200px;
border:1px solid #000000;
margin:0 auto;
color:#808080;
}
#status{
text-align:center;
vertical-align:bottom;
}
.red{
background:#ff0000;
}
.yellow{
background:#ffd800;
}
.green{
background:#00ff21;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Traffic light</title>
</head>
<body onload="loadTraffLight()">
<h1>Traffic light effect demo</h1>
<div id="traffLight">
<label id="status"></label>
</div>
</body>
</html>
关于javascript - 每 3 秒更改一次 div 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38379840/