【案例】自由运动小球

<!DOCTYPE html>

<html lang="en">

<head>

        <meta charset="UTF-8">

        <title>飞翔的小球</title>

        <style>

           *{

                         margin: 0;

                         padding: 0;

                 }

                 #ball{

                         width: 200px;

                         height: 200px;

                         border-radius: 50%;

                         background: pink;

                         position: absolute;

                 }

        </style>

</head>

<body>

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

</body>

<script>

        //获取元素

        var ball = document.getElementById('ball');

        //封装随机函数

        function rand(m,n){

                 return Math.floor(Math.random() * (n - m + 1)) + m;

        }

        //封装改变颜色的函数

        function changeBg(){

                 var r = rand(0,255);

                 var g = rand(0,255);

                 var b = rand(0,255);

                 ball.style.background = 'rgb('+ r +','+ g +','+ b +')';

        }

        changeBg();

        //设置小球运动步径

        var stepX = 2;

        var stepY = 2;

        setInterval(function(){

                 var newLeft = ball.offsetLeft + stepX;

                 var newTop = ball.offsetTop + stepY;

                 var clientWidth = document.documentElement.clientWidth || document.body.clientWidth;

                 var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;

                 if(newLeft >= clientWidth - ball.offsetWidth){

                         stepX *= -1;

                         changeBg();

                 }

                 if(newLeft <= 0){

                         stepX *= -1;

                         changeBg();

                 }

                 if(newTop >= clientHeight - ball.offsetHeight){

                         stepY *= -1;

                         changeBg();

                 }

                 if(newTop <= 0){

                         stepY *= -1;

                         changeBg();

                 }

                 ball.style.left = newLeft + 'px';

                 ball.style.top = newTop + 'px';

        },20);

</script>

</html>

猜你喜欢

转载自www.cnblogs.com/sherryStudy/p/ballFree_move.html