JavaScript实例 躁动的小球


<!doctype html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        html,body{
            margin: 0;
                 padding: 0;
            width: 100%;
            height: 100%;
            background: #000;
            overflow: hidden;
            position: absolute;
        }
        div{
            position: absolute;
            border-radius: 50%;
        }
    </style>

</head>
<body>
 <script type="text/javascript">
    var d1=document.getElementById('d1')
    function Ball(obj){
        this._init(obj);
    }
        Ball.prototype={
            // 初始化
             _init:function(obj){

                // 获取父节点

                this.parentnode=obj.parentNode;
                this.div=document.createElement('div');
                this.r=ranDom(10,70);
                this.x=ranDom(0,1200);

                this.y=ranDom(0,500);

                // 小球背景颜色的设置

                this.color=`rgba(${ranDom(0,255)},${ranDom(0,255)},${ranDom(0,255)},${Math.random()*0.6+0.4})`;       //设置透明度

                // 小球速度设置
                this.speedX=ranDom(-10,20);
                this.speedY=ranDom(-10,20);

            },

            // 显示小球
             show:function(){
                var div=this.div;
                div.style.width=this.r*2+"px";                   //注意这些地方的px一定要加上去   因为CSS的样式为字符串类型 所以要+上“px”;
                div.style.height=this.r*2+"px";
                div.style.background=this.color;
                div.style.left=this.x+"px";
                div.style.top=this.y+"px";
                this.parentnode.appendChild(div);

            },

            // 设置移动
             roll:function(){
                var div=this.div;
                var i=1;
                var j=1;
                var speedX=this.speedX;
                var speedY=this.speedY;
                var maxLeft=this.parentnode.offsetWidth-div.offsetWidth;

                var maxTop=this.parentnode.offsetHeight-div.offsetHeight;

                // 定时器
                setTimeout(function loop(){
                    if(div.offsetLeft>maxLeft|| div.offsetLeft<0){
                        i*=-1;
                    }
                    if(div.offsetTop>maxTop|| div.offsetTop<0){
                        j*=-1;
                    }
                    div.style.left=div.offsetLeft+i*speedX+"px";
                    div.style.top=div.offsetTop+j*speedY+"px";
                    setTimeout(loop,20);
                },20);
            },

        }

        // 设置小球的个数
    for(var i=0;i<20;i++){
        var b2= new Ball({parentNode:document.body});
        b2.show();
        b2.roll();

    }

    // 随机数
    function ranDom(small,big){
        return parseInt(Math.random()*(big-small+1)+small);
    }
    </script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_33744228/article/details/77429444