javascriptのIFステートメントで助けを得たいと思っています。何が起こっているのかというと、ボタンがクリックされても色が変わらないということです。
これが私がやろうとしていることです。次のボタンをクリックすると、次のようになります。
ライトdivの背景色が#ff0000(赤)の場合、#ffff00(琥珀色)に変更する必要があります
ライトdivの背景色が#ffff00(琥珀色)の場合、#00ff00(緑)に変更する必要があります
ライトdivの背景色が#00ff00(緑)の場合、#ff0000(赤)に変更する必要があります
HTML:
<div class="main">
<h1>Traffic Light</h1>
<div class="light">
</div>
</br>
<button id="next" onClick="setBgColour" type="button">Next</button>
</div>
css:
.light
{
background-color: #ff0000;
width: 100px;
height: 20px;
margin-left: auto;
margin-right: auto;
}
JavaScipt:
function setBgColour(){
if(document.getElementsByClassName("light")[0].style.backgroundColor = '#ff0000')
{
document.getElementsByClassName("light")[0].style.backgroundColor = '#ffff00';
}
else if (document.getElementsByClassName("light")[0].style.backgroundColor = '#ffff00')
{
document.getElementsByClassName("light")[0].style.backgroundColor = '#00ff00';
}
else
document.getElementsByClassName("light")[0].style.backgroundColor = '#ff0000';
}
window.onload = function(){
document.getElementById('next').addEventListener('click', setBgColour);
};
これは非常に単純化できます。
var lightnumber = 0; // this variable saves the current state of the traffic light
var lights = [
"#ff0000", "#ffff00", "#00ff00"
]; // this variable saves all possible lights.
setBgColour = function() {
// at first we decide which colour shall be next, so we increase
// the lightnumber by one, except, if we are already at green, then we start over at 0
lightnumber = lightnumber == (lights.length - 1) ? 0 : lightnumber + 1;
// and here we set the light according to our lightnumber variable
document.getElementsByClassName("light")[0].style.backgroundColor = lights[lightnumber];
}
.light {
background-color: #ff0000;
width: 100px;
height: 20px;
margin-left: auto;
margin-right: auto;
}
<h1>Traffic Light</h1>
<div class="light"></div>
</br>
<button id="next" onClick="setBgColour()" type="button">Next</button>
</div>
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加