做一个小球点击可以变色和移动(使用defineProperty设置get和set)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div{
            width: 100px;
            height:100px;
            border-radius: 50%;
            background-color: pink;
            position: absolute;
        }
        .div0{
            background-color: red;
        }
        .div1{
            background-color: aqua;
        }
    </style>
</head>
<body>
<div id="div"></div>
<script>
    //使用defineProperty设置get和set
    var div=document.getElementById("div");//获取div
    div.addEventListener("click",clickHandler);//给div做一个侦听事件
    div._bool=false;//给div这个对象设置一个临时变量
    Object.defineProperty(div,"bool",{
        set:function(value){
            this._bool=value;
            if(!value){
                this.className="div0";
            }else {
                this.className="div1";
            }
        },
        get:function(){
            return this._bool;
        }
    });
    function clickHandler(e) {
       this.bool=!this.bool;
       //也可以使用div.bool=!div.bool;
    }
    //加一个走动的功能
    setInterval(animation,16);
    function animation() {
//        此时的div.bool不可改为this.bool
        if(div.bool) return;//控制走还是停(开关)
        div.style.left=div.offsetLeft+2+"px";
    }
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/hemeng0115/article/details/83618297