我试图通过单击按钮来根据 div 的当前颜色更改其背景颜色。
例如,如果颜色是青色(#00ffff - 它应该更改为黄色('ffff00)。
如果颜色是黄色 - 它应该更改为洋红色 (#ff00ff)。
如果颜色是洋红色 - 它应该恢复为青色。
我已经设法将颜色从青色更改为黄色,但是我不确定如何编写 if 语句(假设 if 语句是最好的方法?)来根据当前颜色更改颜色。
function ColorFunction() {
if (light.getItem("backgroundColor") == '#00ffff') {
document.getElementById("light").style.backgroundColor = "#ffff00";
}
else
if (light.getItem("backgroundColor") == '#ffff00') {
document.getElementById("light").style.backgroundColor = "#ff00ff";
}
else
if (light.getItem("backgroundColor") == '#ff00ff') {
document.getElementById("light").style.backgroundColor = "00ffff";
}
}
.main {
width:250px;
color: #202020;
background-color: #d0d0d0;
}
.light {
width: 50px;
height: 50px;
background-color: #00ffff
}
#burn {
width: 150px;
font-style: italic;
}
#button {
font-style: bold;
width: 150px;
}
<h1>Disco Inferno</h1>
<div class="light" id="light">
div
</div>
<button onClick="ColorFunction()">Burn!</button>
最佳答案
好的,让我们从头开始。
您有一个 id 为 light
的元素,但它不会自动成为您可以在 javascript 中使用的变量。很容易使它成为一个:
var light = document.getElementById("light");
然后,我什至不确定您从哪里获取 getItem
- 也许这是一个猜测 - 但它不是 HTMLElement
上的有效方法。
您可以使用 light.style.backgroundColor
来做到这一点 - 请参阅下面的代码片段。
var colors = ["rgb(0, 255, 255)","rgb(255, 255, 0)","rgb(255, 0, 255)"];
function ColorFunction() {
var light = document.getElementById("light");
var curr = light.style.backgroundColor;
var next = colors.indexOf(curr)+1;
light.style.backgroundColor = colors[next%colors.length];
}
<h1>Disco Inferno</h1>
<div class="light" id="light" style="background-color:#00FFFF">
Burn, baby burn!
</div>
<button onClick="ColorFunction()">Burn!</button>
关于Javascript - 根据当前颜色更改div的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39791577/