点击切换背景颜色(开关灯效果)

本文介绍三种使用JavaScript实现点击元素时背景颜色变化的方法:if...else语句、switch语句及三目运算符,并提供了完整的HTML代码示例。
思路:使用条件语句,符合条件则变色。

一、使用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>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值