JS-碰撞的小球

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .wsx{
            width: 200px;
            height: 200px;
            background-color: red;
            border-radius: 50%;
            position: absolute;
            left: 200px;
            top: 200px;
        }
    </style>
</head>
<body>
    <div class="wsx"></div>
  
    <script>
        //让小球向右下运动
        var wsx = document.querySelector('.wsx')
        //小球运动
        function test(){
            var a = 10 //x
            var b = 10 //y
            //视口宽高
            var docux = document.documentElement.clientWidth
            var docuy = document.documentElement.clientHeight
            //盒子自身宽高
            var left = wsx.clientWidth
            var top = wsx.clientHeight
            //视口宽高-盒子宽高
            var left1 = docux - left
            var top1 = docuy - top

            setInterval(function(){
                //获取盒子距离视口的距离
                var XY = wsx.getBoundingClientRect()
                var x = XY.left
                var y = XY.top
                //写入left和top每次移动距离,每次相加
                var x1 = x + a
                var y1 = y + b

                //需要写入if判断,为了解决大于或者小于视口宽度高度;需要获取视图宽高,以及盒子宽高
                if(x1 > left1){
                    x1 = left1
                    a = -a
                    getrandom()
                }
                if(x1 < 0){
                    x1 = 0
                    a = -a
                    getrandom()
                }
                if(y1 > top1){
                    y1 = top1
                    b = -b
                    getrandom()
                }
                if(y1 < 0){
                    y1 = 0
                    b = -b
                    getrandom()
                }
                //在css写入
                wsx.style.left = x1 +'px'
                wsx.style.top = y1 + 'px'
            },20)
        }
            //写入随机数   让max -min +min
            function num(max,min){
                return Math.floor(Math.random() * (max -min) +min)
            }
            //给盒子写入样式,在上面if语句进行使用
            function getrandom(){
                var r = num(0,256)
                var b = num(0,256)
                var a = num(0,256)
                wsx.style.background = 'rgb('+r+','+b+','+a+ ')'
            }

        test()

    </script>
</body>
</html>

  

posted on 2023-04-10 20:13  爱前端的小魏  阅读(16)  评论(0编辑  收藏  举报

导航