前端--开关灯

342 阅读1分钟

实现的效果:点击时变换颜色,颜色的顺序:red -> green -> yellow -> red

1、基本结构

 <div id="box" style="background: red;"></div>
 <style>
    * {
        margin: 0;
        padding: 0;
    }

    #box {
        width: 200px;
        height: 200px;
        margin: 20px auto;
    }
</style>

2、js实现效果

获得要操作的对象

var box = document.getElementById("box");

2.1 if else实现

 box.onclick = function () {
    let item = box.style.background;
    if (item == "red") {
        box.style.background = "green";
    } else if (item == "green") {
        box.style.background = "yellow";
    } else {
        box.style.background = "red";
    }
}

2.2 switch case 实现

box.onclick = function () {
    let item = box.style.background;
    switch (item) {
        case 'red':
            box.style.background = "green";
            break;
        case 'green':
            box.style.background = "yellow";
            break;
        default:
            box.style.background = 'red';
    }
}

效果