2016-11-29 18 views
2

これは非常に基本的なタイマーですが、タイマーが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; 
} 
+0

ブラウザのinspect要素機能を使用して、クラスが設定されているかどうか確認してください。 –

答えて

1

あなたは正しい考えを持っています!

timeDisplay.classNameを設定しようとすると、追加しようとしている新しいクラスの前にスペースを追加することを忘れないでください。そうしないと、誤って追加されます。

は考えてみましょう:

"oldClass" + "red" // => "oldClassred" bad 
// vs. 
"oldClass" + " red" // => "oldClass red" good 

ですから、ちょうどここredの前にスペースを追加する必要があります。

別のタイプミスあなたの等価比較した:<==はちょうど<=でなければなりません。

if (secondsRemaining <= 10) { 
    timeDisplay.className += " red"; 
} 
+0

ありがとうございます!私は助けてくれることを嬉しく思う@userSufyanうれしい – userSufyan

+0

! –

関連する問題