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>

 

 

转载于:https://www.cnblogs.com/CCxi/p/9464293.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值