javascript 小球碰撞

来源:互联网 发布:juniper network mac 编辑:程序博客网 时间:2024/06/06 08:36

小球起始位置随机,颜色随机
在指定div中运动

html:

<div id="box">    <div id="ball"></div>   </div>

css:

#ball{            width:80px;            height:80px;            background: skyblue;            border-radius: 50%;            position:relative;        }        #box{            width: 500px;            height: 500px;            position: absolute;            top: 10%;            left: 20%;            border: 2px solid #337733;        }

js:

var ball = document.getElementById('ball'),            leftDis = 5;                         topDis = 5;                          leftMax = document.getElementById("box").clientWidth-ball.clientWidth;            topMax = document.getElementById("box").clientHeight-ball.clientHeight;        var box = document.getElementById("box");        ball.style.top = Math.random()*(box.offsetTop,box.offsetHeight+box.offsetTop)+'px';        ball.style.left = Math.random()*(box.offsetLeft,box.offsetWidth+box.offsetLeft)+'px';        setInterval(function(){                          var Left = ball.offsetLeft+leftDis,                    Top = ball.offsetTop+topDis;            if(Left>=leftMax){                               Left = leftMax;                leftDis = -leftDis;                ballColor(ball);                 }else if(Left<=0){                Left = 0;                leftDis = -leftDis;                ballColor(ball);            };            if(Top>=topMax){                Top = topMax;                topDis = -topDis;                ballColor(ball);            }else if(Top<=0){                Top = 0;                topDis = -topDis;                ballColor(ball);            };            ball.style.left = Left+'px';                  ball.style.top = Top+'px';        },30);                                function ballColor(obj){                        var r = Math.floor(Math.random()*256);                g = Math.floor(Math.random()*256);                b = Math.floor(Math.random()*256);               obj.style.backgroundColor = 'rgb('+r+','+g+','+b+')';        }
原创粉丝点击