JS跳动的小球

 

01

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, ini
        ul, ol { list-style: none;}tial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <style>
        a {border: none;text-decoration: none;color: inherit;}
        * {margin: 0;padding: 0;}
        .clearfix:after{content: '';display: block;clear: both;}
        .fl,.fl_child > *{float: left;}
        .fr,.fr_child > *{float: right;}

        body{
            background-color: black;
        }
        p{
            position: absolute;
            left: 0;
            top: 0;
            width: 50px;
            height: 50px;
            background-color: #990FDE;
            border-radius: 50%;
        }
    </style>
    <title>跳动的小球</title>
</head>
<body>
<script>

    /* 动态获取 */
    var aP = document.getElementsByTagName('p');

    /* 创建小球 */
    var length = 30;
     for( var i=0; i<length; i++ ){
        document.body.append(document.createElement('p'));
     }

     /* 初始化步长 */
    var xStep = [];
    var yStep = [];
    for( var i=0; i<length; i++ ){
        xStep[i]= 5+i;
        yStep[i]= 5+i;
    }
    console.log(xStep+"============"+yStep);

    /* 定时器 */
    setInterval(function (){
        /* 小球反弹条件 */
        var Width = document.documentElement.clientWidth -aP[0].clientWidth;
        var Height = document.documentElement.clientHeight -aP[0].clientHeight;

        /*  */
        for( var i=0; i<length; i++ ){
            var left = aP[i].offsetLeft + xStep[i];
            var Top = aP[i].offsetTop + yStep[i];

            /* 碰壁反弹 */
            if(left>Width||left<0){
                left = Math.max(left,0);
                left = Math.min(left,Width);
                xStep[i] = -xStep[i];
                change(i);
            }
            if(Top>Height||Top<0) {
                Top = Math.max(Top, 0);
                Top = Math.min(Top, Height);
                yStep[i] = -yStep[i];
                change(i);
            }
                aP[i].style.left = left + 'px';
                aP[i].style.top = Top + 'px';

            }
    },20)

    /* 小球随机改变颜色 */
    function change(n) {
        var r = Math.floor(Math.random()*256);
        var g = Math.floor(Math.random()*256);
        var b = Math.floor(Math.random()*256);
        aP[n].style.backgroundColor = "rgb("+r+","+g+","+b+")";
    }
</script>
</body>
</html>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冒险岛_0_

您的打赏是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值