亮瞎眼--开关灯升级版

代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        img {
            display: inline-block;
            width: 100px;
            height: 150px;
        }
    </style>
</head>

<body>
    <div id="app"></div>
    <script>
        window.onload = function () {
            var app = document.getElementById('app');

            // 追加50个灯泡
            for (var i = 0; i < 50; i++) {
                app.innerHTML += '<img src="images/bright.jpg" alt="">';
            }

            var imgs = document.getElementsByTagName('img');

            for (var i = 0; i < imgs.length; i++) {
                imgs[i].flag = true;  // 每一个灯泡都配备一个开关 默认值都是 true-亮
                imgs[i].onmouseover = function () {

                    if (this.flag) {  // 判断 当前 img 身上的开关状态 
                        this.src = 'images/dark.jpg';
                        this.flag = false;  // 改变当前img 身上开关状态
                    } else {
                        this.src = 'images/bright.jpg';
                        this.flag = true;
                    }
                }
            }
        }
    </script>
</body>

</html>

 

效果

posted @ 2020-07-03 13:07  石海莹  阅读(199)  评论(0编辑  收藏  举报