so I am trying to create a script in HTML and JavaScript that has a traffic light which changes when a button is presses. I have all the HTML sorted out, but the if /else statement is playing up on me.
Here is the code as it stands:
<!DOCTYPE html>
<html>
<body>
<table border="10px" style="background-color: #000000">
<tr>
<td width="30px" height="30px" style="background-color: #000000" id="1"></td>
</tr>
<tr>
<td width="30px" height="30px" style="background-color: #ecec54" id="2"></td>
</tr>
<tr>
<td width="30px" height="30px" style="background-color: #01db01" id="3"></td>
</tr>
</table>
<p id="temp">1234567890</p>
<button type="button" onclick=changeLights()>Change Lights</button>
</body>
<script>
var lightInfo = ["1","2","3"]
function changeLights() {
var oneState = document.getElementById(lightInfo[0]).getAttribute("style")
var twoState = document.getElementById(lightInfo[1]).getAttribute("style")
var threeState = document.getElementById(lightInfo[2]).getAttribute("style")
document.getElementById("temp").innerHTML = oneState
if (oneState === "background-color: #000000") {
document.getElementById(lightInfo[0]).style.backgroundColor = "#f00000";
}
else {
document.getElementById(lightInfo[0]).style.backgroundColor = "#000000";
}
}
</script>
</html>
PS. The paragraph is just a temporary debugging thing.
So I want the code to get the hexadecimal colour for each data cell to use in the if statement, which works to change the top light from black to red (since I get the hexadecimal for black, which is #000000). However, when I try repeat the process, the colour for the red data cell comes out as some other format (rgb(240,0,0)), which makes the if statement fail and the code break. Is there ay way to make sure the colour is given in a hexadecimal format?
Aucun commentaire:
Enregistrer un commentaire