我正在尝试切换同一div的背景颜色。它确实可以按预期变化(从蓝色到红色(。但是它无法重新切换到红色,并继续在两种颜色之间切换。我知道我应该在第一个if statement中使用" ==",但是当使用" =="时,甚至第一个切换都无法使用。
有什么建议如何使切换重复工作?
function toggleFunction() {
var x = document.getElementById("box");
if (x.style.background == "blue") {
x.style.background = "red";
} else {
x.style.background = "blue";
}
}
.box {
background-color: blue;
width: 100px;
height: 100px;
margin: 30px 0px 0px 30px;
}
<div id="box" class="box" onclick="toggleFunction()"></div>
最简单的解决方案是创建一个名为 red
的新类,并使用classList.toggle
切换该类。这种方法的主要优点是,如果您使用类进行切换,则可以切换更多的CSS
属性,并且还可以扣除您的if-else
比较。
function toggleFunction() {
var x = document.getElementById("box");
x.classList.toggle("red");
}
.box {
background-color: blue;
width: 100px;
height: 100px;
margin: 30px 0px 0px 30px;
}
.red{
background-color: red;
}
<div id="box" class="box" onclick="toggleFunction()"></div>
$( ".box" ).each(function() {
$( this).click(function() {
$( this ).toggleClass( "red" );
});
});
.box {
background: blue;
width: 100px;
height: 100px;
margin: 30px 0px 0px 30px;
}
.box.red {
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="box" class="box"></div>
<div id="box" class="box"></div>