本文實例講述了JS實現的緩沖運動效果。分享給大家供大家參考,具體如下:
	緩沖需要用到數值取整,向上取整:Math.ceil()  向下取整Math.floor()
移動的速度慢慢減慢的效果,移動速度=(終點位置 - 當前位置) / 一個數
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>m.survivalescaperooms.com JS緩沖運動</title><style>#div{  width:150px;  height:150px;  background:#0C6;  position:absolute;  left:0;  top:50px;}#div2{  background:#000;  height:600px;  position:absolute;  left:500px;  width:2px;}</style></head><script>var speed;var time;window.onload = function(){  var btn = document.getElementById('btn');  btn.onclick = function(){    speed = 0;    move(500);  };  btn2.onclick = function(){    speed = 0;    move(0);  };};function move(e){  var div = document.getElementById('div');  clearInterval(time);  time = setInterval(function(){    //改變位置,如果向左則e==500, 向上取整, 否則向右,向下取整,速度=(終點位置 - 當前位置)/一個數    e==500 ? speed = Math.ceil((e-(div.offsetLeft))/30):speed = Math.floor((e-(div.offsetLeft))/30)    if (e <= div.style.left){//達到,關閉定時器      clearInterval(time);    }    else    {      div.style.left = div.offsetLeft+speed+'px';    }  },30);};</script><body><input type="button" value="向右運動" id="btn" /><input type="button" value="向左運動" id="btn2" /><div id = "div"></div><div id = "div2"></div></body></html>點擊此處查看在線演示效果。
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答