点击按钮改变区块颜色

374 阅读1分钟

点击按钮改变区块颜色

 点击按钮改变区块颜色

       面向对象思想:
         找对象,调用其功能,解决问题
         如果没有,自己创建对象,封装功能,解决问题

       自己创建对象,封装功能
          =>1. 创建对象的模板->构造函数
          =>2. new语句创建对象
          
          
 <script>
        function ChangeColor(){
            //面向对象操作dom时,元素定义为属性
            this.btn = document.querySelector('.box1 button')
            this.box = document.querySelector('.box1 div')
            this.onChangecolor = function(color){
                let _this = this
                this.btn.addEventListener('click',function(){
                     _this.box.style.backgroundColor = color
                })
            }
        }
        let c1 = new ChangeColor()
        c1.onChangecolor('blue')
        //面向过程
        function test1() {
            //1.给按钮绑定点击事件
            const btn1 = document.querySelector('.box1 button')
            const box1 = document.querySelector('.box1 div')
            btn1.addEventListener('click', function () {
                //改变div区块颜色
                box1.style.backgroundColor = 'blue'
            })
        }
        // test1()
    </script>