为什么当我第一次点击div
元素工作时,background-color
发生了变化,但第二次没有变回?
<body>
<div id="box1" onclick="changeBack(Colors[0], 'box1')" ondragenter=""></div>
<script>
var Colors = ["white"];
function changeBack (color, id) {
if (color === "white") {
color = "black";
document.getElementById(id).style.backgroundColor = "black";
} else if (color === "black") {
color = "white";
document.getElementById(id).style.backgroundColor = "white";
}
}
</script>
</body>
不要用这种方式调用处理程序:
onclick="changeBack(Colors[0], 'box1')"
您可以简化为:
onclick="changeBack(this)"
this关键字指的是当前元素,在您的案例中为box1。
为了改变颜色,你可以简单地测试当前背景颜色的值:
function changeBack (ele) {
var color = (ele.style.backgroundColor || 'white') == 'white' ? 'black' : 'white';
ele.style.backgroundColor = color;
}
div {
border: thick solid #0000FF;
height: 100px;
}
<div id="box1" onclick="changeBack(this)" ondragenter=""></div>
<body>
<div id="box1" data-state="white"></div>
<script>
const div= document.getElementById('box1');
div.addEventListener('click', function(){
console.log('clicked');
const state = div.getAttribute('data-state');
const newState = state == "white" ? "black":"white";
div.style.backgroundColor = newState;
div.setAttribute('data-state', newState);
});
</script>
</body>