美文网首页
10 js动画小球反弹的案例

10 js动画小球反弹的案例

作者: An的杂货铺 | 来源:发表于2019-03-12 18:08 被阅读0次
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Document</title>
 <style>
      * {
          padding: 0;
          margin: 0;
      }

      div {
          width: 28px;
          height: 28px;
          border-radius: 50%;
          background-color: red;
          position: absolute;
          left: 0;
          top: 200px;
      }
 </style>
</head>
<body>
 <button id="fly">Flying</button>
 <div id="ball"></div>
 <script>
     function $(id){
         return document.getElementById(id);
     }
     var ball = $('ball');
     var speedX = 10;speedY = -5;
     var totalW = document.documentElement.clientWidth||document.body.clientWidth;
         // 或window.innerWidth
     var totalH = document.documentElement.clientHeight||document.body.clientHeight;
        // 或window.innerHeight
     var timer = setInterval(function(){
         ball.style.left = ball.offsetLeft+speedX+'px';
         ball.style.top = ball.offsetTop+speedY+'px';
         var maxW = totalW - ball.offsetWidth;
         var maxH = totalH - ball.offsetHeight;
         if(ball.offsetLeft>=maxW){
             ball.style.left = maxW+'px';
             speedX*=-1;
         }else if(ball.offsetLeft<=0){
              ball.style.left = 0+'px';
              speedX*=-1;
         }
         if(ball.offsetTop>=maxH){
             ball.style.top = maxH+'px';
             speedY*=-1;
         }else if(ball.offsetTop<=0){
              ball.style.top = 0+'px';
              speedY*=-1;
         }

     },20)

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

如下图


one.gif

相关文章

网友评论

      本文标题:10 js动画小球反弹的案例

      本文链接:https://www.haomeiwen.com/subject/xcwnpqtx.html