
分享一个用原生JS实现的缓冲运动的小Demo,效果如下:

以下是代码实现,欢迎大家复制粘贴及吐槽。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>原生JS实现各种运动之缓冲运动</title>
<style>
#div1 {
width: 100px;
height: 100px;
position: absolute;
background: red;
left: 0;
top: 50px;
}
</style>
<script type="text/javascript">
var timer = null;
function startMove(iTarget) {
var oDiv = document.getElementById('div1');
clearInterval(timer);
timer = setInterval(function () {
var iSpeed = (iTarget - oDiv.offsetLeft) / 8;
iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
//是否到达终点
if (oDiv.offsetLeft == iTarget) {
// 到达终点
clearInterval(timer);
} else {
// 到达之前
oDiv.style.left = oDiv.offsetLeft + iSpeed + 'px';
}
// 以标题的形式打印出来
// document.title=oDiv.offsetLeft+',speed='+iSpeed;
}, 30);
}
</script>
</head>
<body>
<input type="button" value="开始运动" onclick="startMove(300)" />
<div id="div1"></div>
</body>
</html>