• JS简单回弹原理


     1 /*
     2 *JS简单回弹原理
     3 */
     4 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     5 <html xmlns="http://www.w3.org/1999/xhtml">
     6 <head>
     7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     8 <title>无标题文档</title>
     9 <style type="text/css">
    10 *{ padding:0; margin:0;}
    11 #div1 { 100px; height:100px; position:absolute; background:red;}
    12 </style>
    13 
    14 <script type="text/javascript">
    15 window.onload = function (){
    16     startMove("div1");
    17     function startMove(id){
    18          var iSpeedX = 10;
    19          var iSpeedY = 10;
    20         setInterval(function(){
    21             var oDiv = document.getElementById(id);
    22              
    23              var l = oDiv.offsetLeft + iSpeedX;    //物体在X方向上的位移
    24              var t = oDiv.offsetTop + iSpeedY;    //物体在Y方向上的位移
    25              
    26             document.title = l + " , " + t + " , " + iSpeedX + " , " + iSpeedY;    //在标题栏显示位移坐标和当前在X、Y方向上的速度
    27             
    28              if(t > document.documentElement.clientHeight - oDiv.offsetHeight){    //判断物体在Y方向上是否超出屏幕可视区的底部
    29                 t =  document.documentElement.clientHeight - oDiv.offsetHeight;
    30                 iSpeedY *= -1;                                //改变当前在Y方向上的速度、回弹
    31              }else if(t < 0){                                  //判断物体在Y方向上是否超出屏幕可视区的顶部
    32                 t = 0;
    33                 iSpeedY *= -1;                                 //再改变当前在Y方向上的速度、回弹 
    34              }
    35              if(l > document.documentElement.clientWidth - oDiv.offsetWidth){      //判断物体当前在X方向上是否超出屏幕可视区的右边
    36                 l = document.documentElement.clientWidth - oDiv.offsetWidth;
    37                 iSpeedX *= -1;                                  //改变当前在X方向上的速度、回弹
    38              }else if(l < 0){                                  //判断物体当前在X方向上是否超出屏幕可视区的左边
    39                 l = 0;
    40                 iSpeedX *= -1;                                 //改变当前物体在X方向上的速度、回弹
    41              }
    42               
    43              oDiv.style.left = l + "px";
    44              oDiv.style.top = t + "px";
    45                      
    46         },30);
    47     }
    48 }
    49 </script>
    50 </head>
    51 
    52 <body>
    53 
    54 <div id="div1"></div>
    55 
    56 </body>
    57 </html>

    • 给物体初始一个在X、Y方向上的运动速度。
    • 通过定时器改变物体左右坐标改变left、top的值来实现位移效果
    • 判断物体是否超出可视区的边界值(改变物体在X、Y方向的速度)
  • 相关阅读:
    C++基础-函数的覆盖和函数重载
    C++基础-public(公有属性),protected(保护属性),private(私有属性)
    C++基础-父类和子类的构造和析构的顺序
    C++基础-类的(有参数)继承
    C++基础-类的(无参数)继承
    C程序之包含头文件
    时间复杂度详细分析
    "分辨率"到底是个什么概念?它和DPI之间是什么关系?
    每天一个Qt类之QWidget
    line1: 1: Syntax error: word unexpected (expecting ")")
  • 原文地址:https://www.cnblogs.com/xy404/p/3622635.html
Copyright © 2020-2023  润新知