我想使用javascript进行灯光开关
当背景颜色为:
“white”=>打开
“黑色”=>关闭
问题:我的代码可以关灯,但我不知道如何打开它。
我有一个想法到最后,但它不起作用。如何解决?
这是我的代码。
HTML
<!DOCTYPE HTML>
<html lang="en">
<head>
<mate charset="utf-8" />
<title>light Switch</title>
<link rel="stylesheet" href="lightSwitch.css" />
</head>
<body>
<!--
<a href="javascript:void(0)" id="lightOn">turn on</a>
</br>
<a href="javascript:void(0)" id="lightOff">turn off</a>
</br>
-->
<a href="javascript:void(0)" id="lightSwitch">The switch</a>
<script src="lightSwitch.js"></script>
</body>
</html>
CSS
body{
background-color: white;
margin: 0;
padding: 0;
}
#lightSwitch{
width: 300px;
height: 25px;
text-align: center;
border: 1px solid black;
padding: 5px;
text-decoration: none;
position: absolute;
top: 50%;
left: 50%;
margin: -15px 0 0 -152.5px;
}
的javascript
function lightSwitch(){
var light = document.getElementById("lightSwitch");
var BGcolor = document.body.style.backgroundColor;
if (BGcolor != "black"){
light.innerHTML = "The light is open! Click here to close.";
light.onclick = function(){
document.body.style.backgroundColor = "Black";
light.innerHTML = "The light is close! Click here to open.";
}
}
}
lightSwitch();
我有个主意,看看:
function lightSwitch(){
var light = document.getElementById("lightSwitch");
var BGcolor = document.body.style.backgroundColor;
if (BGcolor != "black"){
light.innerHTML = "The light is open! Click here to close.";
light.onclick = function(){
document.body.style.backgroundColor = "Black";
light.innerHTML = "The light is close! Click here to open.";
}else{
light.onclick = function(){
document.body.style.backgroundColor = "white";
}
}
}
}
lightSwitch();
答案 0 :(得分:0)
你的代码太复杂了。定义一个CSS类并根据需要分配该类。
我创建了一个demo(在Codepen)来展示我的想法。希望这会有所帮助。
JavaScript部分作为预览:
document.getElementById('switch').addEventListener('click', function() {
if (this.classList.contains('off')) {
// switch on
this.classList.remove('off');
} else {
// switch off
this.classList.add('off');
}
});
通过切换课程,您可以获得更多,而不仅仅是更改一个属性,如演示所示。
答案 1 :(得分:0)
我简化了代码。 DEMO
<div id="container"></div><button id="lightSwitch">Switch</button>
var swit = document.getElementById('lightSwitch');
var container = document.getElementById('container');
swit.onclick = function(){
var color = container.style.backgroundColor;
if(color === 'white'){
container.style.backgroundColor = 'black';
}else{
container.style.backgroundColor = 'white';
}
};