用javascript实现缓冲运动

用javascript实现一个小功能。如下效果显示:当鼠标移动到div上时,div变宽;当鼠标移除div时,div恢复原来的宽度,可用缓冲运动实现。

缓冲运动的原理是:当div宽度逐渐变宽到目标宽度时,速度越来越慢,直至停止,即速度和距离目标点的距离成正比。

 

 1 var timer = null;
 2 function startMove(iTarget)
 3 {
 4     var oDiv = document.getElementById("div1");
 5     clearInterval(timer);
 6     timer = setInterval(function()
 7         {
 8             var iSpeed = (iTarget-oDiv.offsetWidth)/8;
 9             iSpeed = iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed);
10             if (iTarget == oDiv.offsetWidth)
11             {
12                 clearInterval(timer);
13             }
14             else
15             {
16                 oDiv.style.width = oDiv.offsetWidth + iSpeed +"px";
17             }
18         },30)
19 }

 

将速度iSpeed和目标点iTarget设为参数,方便传入数据。代码用定时器来实现。

首先速度是目标点减去div的宽度,再除以8的原因是直接相减会导致速度非常大,这样运动会直接到达目标点,没有中间的过程。

除以8会有小数点的情况,需要Math.ceil()向上取整,Math.floor()向下取整。

div变宽向上取整,div变回原来的宽度则向下取整。

再添加onmousemove和onmouseout事件将iTarget参数传入startMove函数中。

上完整代码:

 1 <!DOCTYPE html>
2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 <style> 7 #div1 8 { 9 position: absolute; 10 width: 300px; 11 height: 200px; 12 background-color: blue; 13 } 14 </style> 15 <script> 16 window.onload = function() 17 { 18 var oDiv = document.getElementById("div1"); 19 oDiv.onmousemove = function() 20 { 21 startMove(500) 22 } 23 oDiv.onmouseout = function() 24 { 25 startMove(300) 26 } 27 } 28 var timer = null; 29 function startMove(iTarget) 30 { 31 var oDiv = document.getElementById("div1"); 32 clearInterval(timer); 33 timer = setInterval(function() 34 { 35 var iSpeed = (iTarget-oDiv.offsetWidth)/8; 36 iSpeed = iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed); 37 if (iTarget == oDiv.offsetWidth) 38 { 39 clearInterval(timer); 40 } 41 else 42 { 43 oDiv.style.width = oDiv.offsetWidth + iSpeed +"px"; 44 } 45 },30) 46 } 47 </script> 48 </head> 49 <body> 50 <div id="div1"></div> 51 </body> 52 </html>
posted @ 2018-03-06 14:24  amberriver  阅读(187)  评论(0编辑  收藏  举报