Home >Web Front-end >JS Tutorial >js animation learning (2)

js animation learning (2)

黄舟
黄舟Original
2016-12-30 16:55:001036browse

4. Buffering motion of simple animation



realizes the buffering of speed, that is, the speed of different positions is different. The closer to the target value, the smaller the speed, so the speed value and target value are different from the current The difference in values ​​is proportional. One thing to note here is that the speed of an object changes continuously during motion, and does not change according to an integer. When the object stops, due to decimal reasons, the position may not return to the original starting point, but will be a little worse, so the change in the motion is buffered The speed should be rounded up.

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

Call the above JS function in the HTML document below. Let’s use the div from last time as an example:

<style type="text/css">
     *{
         margin: 0;
         padding: 0;
     }
     
     #box1{
         width: 200px;
         height: 200px;
         background-color: red;
         position: absolute;
         left: 0;
     }
     
 </style>
<div id="box1"></div>
 <script type="text/javascript">
     window.onload=function(){
         var ob=document.getElementById(&#39;box1&#39;);
         ob.onmouseover=function(){
             Move(200);
         }  
         ob.onmouseout=function(){
             Move(0);
         }  
     }
 </script>

The above is the content of js animation learning (2). For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:js animation learning (1)Next article:js animation learning (1)