js用循环将三个Div变成红色

编程目的:点击按钮将三个div变成红色 

<!DOCTYPE html>
<html>
    <head>
        <title>用循环将三个Div变成红色</title>
        <style type="text/css">
            *{ margin: 0px; padding: 0px; text-align: center; }
            #app4{ width: 336px; height: 162px; position: relative; margin: 0 auto; }
            #app4 button{ width: 150px; height: 30px; position: absolute; top: 15px; left: 93px; cursor: pointer; }
            #app4 div{ width: 100px; height: 100px; float: left; background: black; top: 50px; position: relative; border: 6px solid #ffffff;}
        </style>
    </head>
    <body>
        <div id="app4">
            <button>点击将div改变成红的</button>
            <div></div>
            <div></div>
            <div></div>
        </div>

        <script type="text/javascript">
            // 判断状态
            var judge = false;
            window.onload = function(){
                // 获取元素
                var changeColorBtn = document.getElementById("app4").getElementsByTagName("button")[0];
                var colorDiv = document.getElementById("app4").getElementsByTagName("div");
                // 执行点击事件
                changeColorBtn.onclick = function(){
                    // 遍历div
                    for(var i = 0; i < colorDiv.length; i++){
                        if(!judge){
                            // 进行更改操作
                            colorDiv[i].style.backgroundColor = "red";
                            this.innerHTML = "点击将div改变成黑的";
                        }
                        if(judge){
                            colorDiv[i].style.backgroundColor = "black";
                            this.innerHTML = "点击将div改变成红的";
                        }
                    }
                    judge = !judge;
                }
            }
            
        </script>
    </body>
</html>

                                       效果图:

                                            

猜你喜欢

转载自blog.csdn.net/qq_44254672/article/details/90483469