这是一个非常基本的计时器,但我想知道是否有任何方法可以在计时器达到 10 秒时将显示颜色更改为红色。我尝试将这段代码放在 javascript 中的不同位置,以尝试在元素中放置一个类,但它只是搞砸了。
if (secondsRemaining <== 10) {
timeDisplay.className += "red";
}
这是我的 javascript:
var secondsRemaining;
var intervalHandle;
function resetPage() {
document.getElementById("inputArea").style.display = "block";
}
function tick() {
var timeDisplay = document.getElementById("time");
var min = Math.floor(secondsRemaining / 60);
var sec = secondsRemaining - (min * 60);
if (sec < 10) {
sec = "0" + sec;
}
var message = min + ":" + sec;
timeDisplay.innerHTML = message;
if (secondsRemaining === 0) {
alert("Done!");
clearInterval(intervalHandle);
resetPage();
}
// subtracts seconds remaining
secondsRemaining--;
}
function startCountdown() {
var minutes = document.getElementById("minutes").value;
if (isNaN(minutes)) {
alert("Please enter a number");
return;
}
if (minutes == "") {
alert("Please enter a number");
return;
}
secondsRemaining = minutes * 60;
intervalHandle = setInterval(tick, 1000);
document.getElementById("inputArea").style.display = "none";
}
window.onload = function() {
var inputMinutes = document.createElement("input");
inputMinutes.setAttribute("id", "minutes");
inputMinutes.setAttribute("type", "text");
var startButton = document.createElement("input");
startButton.setAttribute("type", "button");
startButton.setAttribute("value", "Start Countdown");
startButton.onclick = function() {
startCountdown();
};
document.getElementById("inputArea").appendChild(inputMinutes);
document.getElementById("inputArea").appendChild(startButton);
};
HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>Countdown</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="container">
<div id="inputArea"></div>
<h1 id="time">0:00</h1>
</div>
<script src="script.js"></script>
</body>
</html>
CSS:
body {
font-family: Roboto;
font-size: 100%
color: rgb(33, 33, 33);
}
#container {
width: 400px;
margin: auto;
}
#time {
font-size: 100px;
}
.red {
color: red;
}
最佳答案
你的想法很对!您的代码中只有一个小错误:
当您尝试设置 timeDisplay.className
时, 不要忘记在您尝试添加的新类之前添加一个空格——否则它会不正确地追加。
考虑:
"oldClass" + "red" // => "oldClassred" bad
// vs.
"oldClass" + " red" // => "oldClass red" good
所以只需要在red
前加一个空格即可这里:
另一个错字是你的平等比较:<==
应该只是 <=
.
if (secondsRemaining <= 10) {
timeDisplay.className += " red";
}
关于javascript - 如何改变显示器的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40856307/