if-else案例–开关灯

首先,在创建一个html页面,创建一个div盒子,用css设置相应的样式,用js获取盒子的元素,通过点击事件,设置body的背景颜色,用if..else来判断当什么状态设置相应的颜色,(swith...case同理)
 
break:跳出当前循环
continue:结束本次循环
 
.css
<style type="text/css">
*{
margin: 0;
padding: 0;
}
html,body{
width:100%;
height:100%;
background: white;
}
#box{
width:100px;
height:100px;
margin:50px auto;
background: red;
text-align: center;
line-height: 100px;
color:white;
cursor: pointer;
}
</style>

.html

<div id="box">点我啊</div>

.js

<script>
// 操作谁,就要先获取谁
var oBox = document.getElementById("box");
// 给oBox这个元素绑定一个点击事件;当点击这个盒子的时候,触发后面的function里面的代码;
// 获取body 元素:document.body
console.log(document.body);
oBox.onclick = function () {
// 当页面现在是白色时,让它变成黑色,
// 如果本来就是黑色,让它变成白色;
// 获取
//{style:{background:""}}
var curBg = document.body.style.background;
console.log(curBg);
/* if(curBg=="" || curBg=="white"){
console.log(100);
document.body.style.background = "black";
}else if(curBg=="black"){
console.log(200);
document.body.style.background = "red";
}else if(curBg==="red"){
document.body.style.background = "white";
}*/
switch (curBg){
case "":
document.body.style.background = "black";
break;
case "black":
console.log("red");
document.body.style.background = "red";
break;
case "red":
document.body.style.background = "white";
break;
case "white":
document.body.style.background = "";
break;
}
}
// 黑白
// 红-->黄色-->蓝色--> 黑色-->红
// 先用if else 在用switch case;
 
</script>
 

猜你喜欢

转载自www.cnblogs.com/CCxi/p/9464293.html