zoukankan      html  css  js  c++  java
  • js动画学习(二)

    四、简单动画之缓冲运动

         

          实现速度的缓冲,即不同位置的速度不同,越靠近目标值速度越小,所以速度值与目标值与当前值之差成正比。这里要注意一个问题就是物体在运动中速度是连续变化的,不是按照整数变化的,当物体停止时由于小数的原因,位置可能不会回到原起点,会差一点,所以缓冲运动里变化的速度要取整。

     1 //鼠标移到元素上元素右移,鼠标离开元素回去。
     2 var timer="";
     3 function Move(locat) {//移动终点位置
     4     var ob=document.getElementById('box1');
     5     clearInterval(timer);
     6     timer=setInterval(function () {
     7         var speed=(locat-ob.offsetLeft)/10;//speed的大小和移动距离成正比,分母控制缓冲的快慢,即比例系数K,可调整
     8         speed=speed>0?Math.ceil(speed):Math.floor(speed);//凡是缓冲运动速度一定要取整!!!向右运动时坐标向上取整,向左运动时坐标向下取整
     9         if (ob.offsetLeft==locat) {//当前位置到达指定终点,关闭定时器
    10             clearInterval(timer);            
    11         } else {
    12             ob.style.left=ob.offsetLeft+speed+'px';
    13         }
    14     }, 30)
    15 }

          在下面的HTML文档里调用上面的JS函数。还用上次的那个div为例:

     1 <style type="text/css">
     2     *{
     3         margin: 0;
     4         padding: 0;
     5     }
     6     
     7     #box1{
     8         width: 200px;
     9         height: 200px;
    10         background-color: red;
    11         position: absolute;
    12         left: 0;
    13     }
    14     
    15 </style>
     1 <div id="box1"></div>
     2 <script type="text/javascript">
     3     window.onload=function(){
     4         var ob=document.getElementById('box1');
     5         ob.onmouseover=function(){
     6             Move(200);
     7         }  
     8         ob.onmouseout=function(){
     9             Move(0);
    10         }  
    11     }
    12 </script>

     

  • 相关阅读:
    ASP.NET 2.0中使用webpart系列控件
    ASP.NET AJAX入门系列(11):在多个UpdatePanle中使用Timer控件(转)
    WebService SoapHeader的使用
    (转)对程序员职业的一些建议
    android组件间通信
    关于android library project
    (转)我6个月的学习编程经历:从”大齿怪“到“狂欢者”
    DOM的一个要注意的地方
    android的休眠对service,activity的影响
    java的字符串和char数组
  • 原文地址:https://www.cnblogs.com/csxiaoyu/p/5203436.html
Copyright © 2011-2022 走看看