• JS 触碰反弹


     1 <!DOCTYPE html>
     2 <html>
     3     <head>
     4         <meta charset="UTF-8">
     5         <title></title>
     6         <style type="text/css">
     7             *{
     8                 padding: 0;
     9                 margin: 0;
    10             }
    11             #box{
    12                 width: 500px;
    13                 height: 400px;
    14                 border: 1px solid gainsboro;
    15                 margin: 20px auto  0;
    16                 position: relative;
    17             }
    18             #ball{
    19                 width: 30px;
    20                 height: 30px;
    21                 border-radius: 50%;
    22                 background: red;
    23                 position: absolute;
    24             }
    25         </style>
    26     </head>
    27     <body>
    28         <div id="box">
    29             <div id="ball"></div>
    30         </div>
    31     </body>
    32     <script type="text/javascript">
    33         // 获取 box 和 ball
    34         var box = document.getElementById("box");
    35         var ball = document.getElementById("ball");
    36         var speedX = 0;
    37         // 获取小球的初始 left
    38         var originLeft = ball.offsetLeft;
    39         // ball 最大的移动宽度
    40         var maxWidth =  box.clientWidth - ball.offsetWidth;
    41         // ball 可以移动的最大高度
    42         var maxheight = box.clientHeight - ball.offsetHeight;
    43         // 定义一个增量(x)
    44         var add = 5;
    45         // 定义纵向的移动记录值
    46         var speedY = 0;
    47         // 定义增量2(Y)
    48         var dda = 10;
    49         // 获取小球的初始 top
    50         var originTop = ball.offsetTop;
    51         
    52         setInterval(function(){
    53             speedX += add;
    54             speedY += dda;
    55             
    56             // 调整 ball 的 left 让他向右移动
    57             if(speedX >= maxWidth){
    58                 add = -add;    
    59             }
    60             
    61             if(speedX <= 0){
    62                 add = -add;
    63             }
    64             
    65             if(speedY >= maxheight){
    66                 dda = -dda;
    67             }
    68             if(speedY <= 0){
    69                 dda = -dda;
    70             }
    71             
    72             ball.style.left = originLeft + speedX + "px"; 
    73             ball.style.top = originTop + speedY + "px";
    74             
    75         },30);
    76     </script>
    77 </html>
  • 相关阅读:
    爬虫简介
    MongoDb安装pymongo和mongoengine使用
    简单使用WebSocket实现聊天室
    DBUtils
    FLASK 的Session和MoudelForm插件
    第十一篇 CBV和闪现
    HDOJ 4699 Editor 对顶栈
    [NOI1999]内存分配
    横截面图
    STL List Set
  • 原文地址:https://www.cnblogs.com/PowellZhao/p/5627146.html
Copyright © 2020-2023  润新知