【案例】自由运动小球

【案例】自由运动小球,第1张

概述<!DOCTYPE html> <html lang="en"> <head>         <meta charset="UTF-8">         <title>飞翔的小球</title>         <style>            *{                          margin: 0;                          padding:

<!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>

总结

以上是内存溢出为你收集整理的【案例】自由运动小球全部内容,希望文章能够帮你解决【案例】自由运动小球所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1079720.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存