1. 主页
  2. 文档
  3. JS
  4. 面向对象
  5. js案例红绿灯

js案例红绿灯

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="box">

    </div>

    <script>
        //红绿灯的类
        function hld() {
            //颜色属性
            this.color = 1;
            //初始化方法。
            this.init();
            // 绑定监听
            this.bindEvent();
        }
        //原型初始化方法做什么
        hld.prototype.init = function() {
            this.dom = document.createElement('img');
            this.dom.src = 'images/' + this.color + '.jpg';
            bx.appendChild(this.dom);

        }

        hld.prototype.bindEvent = function() {
            var self = this;
            this.dom.onclick = function() {
                self.alcu();
            }
        }

        hld.prototype.alcu = function() {
                this.color++;
                if (this.color == 4) {
                    this.color = 1;
                }
                // 光color属性变化没有用,还要更改自己的dom的src属性
                this.dom.src = 'images/' + this.color + '.jpg';
            }
            //选择盒子
        var bx = document.getElementById('box');

        // 实例化100个
        var count = 100;

        while (count--) {
            new hld();
        }
    </script>
</body>

</html>
这篇文章对您有用吗?

我们要如何帮助您?