JS實現(xiàn)的緩沖運動效果示例
本文實例講述了JS實現(xiàn)的緩沖運動效果。分享給大家供大家參考,具體如下:
緩沖需要用到數(shù)值取整,向上取整:Math.ceil() 向下取整Math.floor()
移動的速度慢慢減慢的效果,移動速度=(終點位置 - 當前位置) / 一個數(shù)
<!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>www.dhdzp.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, 向上取整, 否則向右,向下取整,速度=(終點位置 - 當前位置)/一個數(shù)
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>
點擊此處查看在線演示效果。
或者使用本站在線HTML/js運行工具測試查看運行效果:http://tools.jb51.net/code/HtmlJsRun
更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript運動效果與技巧匯總》、《JavaScript切換特效與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript錯誤與調試技巧總結》、《JavaScript數(shù)據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數(shù)學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
相關文章
細數(shù)promise與async/await的使用及區(qū)別說明
這篇文章主要介紹了細數(shù)promise與async/await的使用及區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07

