<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div{
height: 100px;
width: 100px;
position:absolute;
left: 0px;
top:0px;
background: orange;
}
button{
margin-top: 200px;
}
span{
width: 2px;
height: 100px;
position: absolute;
left: 300px;
top:0px;
background: black;
}
</style>
</head>
<body>
<div id='demo'></div>
<button id='btn'>run</button>
<span></span>
<script>
//bug1:連續多點btn,會導致一直加速。
//bug2: 連續點擊btn,會導致卡一下走一下。
//bug3: 不能完美停在線上
var timer = null;
btn.onclick = function () {
startMove(demo,300);
}
//緩衝運動
function startMove(dom, iTarget) {
clearInterval(timer);//防止多次點擊加速
var iSpeed;
timer = setInterval(function () {
iSpeed = (iTarget - dom.offsetLeft) / 10;
if (iSpeed > 0) {
iSpeed = Math.ceil(iSpeed);
}else {
iSpeed = Math.floor(iSpeed);
}
if (dom.offsetLeft === iTarget) {
clearInterval(timer);
}else {
dom.style.left = dom.offsetLeft + iSpeed + 'px';
}
}, 30);
}
</script>
</body>
</html>
JS緩衝運動
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.