思路:使用条件语句,符合条件则变色。
一、使用if…else
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>点击切换背景颜色</title>
</head>
<body>
<!--设置一个背景颜色为红,宽200高200像素的盒子-->
<div id="box" style="width:200px;height:200px;background:red;"></div>
<script type="text/javascript">
var oDiv=document.getElementById("box");
oDiv.onclick=function(){
var bg=oDiv.style.backgroundColor;
if(bg=='red'){
oDiv.style.backgroundColor='blue';
}else if(bg=='blue'){
oDiv.style.backgroundColor='yellow';
}else{
oDiv.style.backgroundColor='red';
}
}
</script>
</body>
</html>
二、使用switch语句
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>点击切换背景颜色</title>
</head>
<body>
<div id="box" style="width:200px;height:200px;background:red;"></div>
<script type="text/javascript">
var oDiv=document.getElementById("box");
oDiv.onclick=function(){
var bg=oDiv.style.backgroundColor;
switch(bg){
case 'red':
oDiv.style.backgroundColor='blue';
break;
case 'blue':
oDiv.style.backgroundColor='green';
break;
default:
oDiv.style.backgroundColor='red';
}
}
</script>
</body>
</html>
三、使用三目运算符
三目运算符的语法:variable = boolean_expression ? true_value : false_value;
true_value或false_value为空时,可用void(0)占位。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>点击切换背景颜色</title>
</head>
<body>
<div id="box" style="width:200px;height:200px;background:red;"></div>
<script type="text/javascript">
var oDiv=document.getElementById("box");
oDiv.onclick=function(){
var bg=oDiv.style.backgroundColor;
//三目运算符1,背景色点击从红变蓝
bg=='red'?oDiv.style.backgroundColor='blue':oDiv.style.backgroundColor='red';
//三目运算符2,红—>蓝—>黑—>红
bg=='red'?oDiv.style.backgroundColor='blue':void(0);
bg=='blue'?oDiv.style.backgroundColor='black':void(0);
bg=='black'?oDiv.style.backgroundColor='red':void(0);
}
</script>
</body>
</html>