【发布时间】:2016-10-19 11:44:50
【问题描述】:
所以我正在尝试用 HTML 和 JavaScript 创建一个脚本,该脚本有一个红绿灯,当按下按钮时会发生变化。我已经整理好所有的 HTML,但是 if /else 语句在我身上发挥作用。
下面是代码:
<!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。该段只是一个临时调试的东西。
所以我希望代码获取每个数据单元格的十六进制颜色以在 if 语句中使用,这可以将顶灯从黑色更改为红色(因为我得到了黑色的十六进制颜色,即 #000000)。但是,当我尝试重复该过程时,红色数据单元格的颜色显示为其他格式 (rgb(240,0,0)),这使得 if 语句失败并且代码中断。有没有办法确保颜色以十六进制格式给出?
【问题讨论】:
标签: javascript html hex rgb