javascript 小球碰撞

小球起始位置随机,颜色随机
在指定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+')';
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值