当我使用JavaScript单击事件监听器时,我试图在两种颜色之间进行切换。当我触发click
事件时,它会将颜色更改为黑色。当我再次点击它时,我希望它改回默认值,即白色。我认为涉及if语句,但我不确定逻辑在这种情况下如何工作。
<!DOCTYPE html>
<html>
<head>
<title>Light Switch</title>
<link rel="stylesheet" href="light.css" />
</head>
<body id="body">
<button id="submit">Submit
<label id="switch">
<input type="checkbox" checked>
<span class="slider"></span>
</label>
</button>
<script src="light.js"></script>
</body>
</html>
function start() {
var submit = document.getElementById("submit");
submit.addEventListener("click", toggle);
};
function toggle() {
var color = document.getElementById("body");
color.style.backgroundColor = "black";
};
start();
答案 0 :(得分:4)
您可以在该元素的toggle
上使用classList
函数。添加一个类并切换它。
function start() {
var submit = document.getElementById("submit");
submit.addEventListener("click", toggle);
};
function toggle() {
var color = document.getElementById("body");
color.classList.toggle('black');
};
start();
.black {
background-color: black;
}
<body id="body">
<button id="submit">Submit
<label id="switch">
<input type="checkbox" checked>
<span class="slider"></span>
</label>
</button>
</body>
您也可以只检查当前颜色并每次切换。
function start() {
var submit = document.getElementById("submit");
submit.addEventListener("click", toggle);
};
function toggle() {
var color = document.getElementById("body");
var backColor = color.style.backgroundColor;
color.style.backgroundColor = backColor === "black" ? "white" : "black";
};
start();
<body id="body">
<button id="submit">Submit
<label id="switch">
<input type="checkbox" checked>
<span class="slider"></span>
</label>
</button>
</body>
答案 1 :(得分:2)
您可以使用classList
属性
backgroundColor
function start() {
var submit = document.getElementById("submit");
submit.addEventListener("click", toggle);
};
function toggle() {
var color = document.getElementById("body");
color.classList.toggle("black");
};
start();
.black {
background-color: black;
}
<div id="body">
<button id="submit">Submit
<label id="switch">
<input type="checkbox" checked>
<span class="slider"></span>
</label>
</button>
</div>
答案 2 :(得分:0)
这样做,我觉得它对你有用......
var background = document.getElementById(id).style.background;
var btn = addEventListener("click", function (){
if(background = "rgb(255,145,0)"){
document.getElementById(id).style.background = "red";
}
else
{
document.getElementById(id).style.background = "white";
}
});
答案 3 :(得分:0)
function start() {
var submit = document.getElementById("submit");
submit.addEventListener("click", toggle);
};
function toggle() {
var color = document.getElementById("body");
if(color.style.backgroundColor==='black')
color.style.backgroundColor='';
else
color.style.backgroundColor = "black";
};
start();
&#13;