缓冲运动就是运动的速度与时间或者距离有关联,不是一般的匀速运动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>缓冲动画</title>
<style>
.animation{
background-color: green;
height: 100px;
width: 100px;
left: 0px;
top: 0px;
position: absolute;
}
</style>
</head>
<body>
<div id="test" class="animation">animation</div>
</body>
<script type="text/javascript">
window.onload = function(){
var ele = document.getElementById("test"),
timer = null ,
WINDOW_WIDTH = window.innerWidth - 100,
target = WINDOW_WIDTH;
ele.onmouseover = function(){
startAnimation();
}
function startAnimation(){
clearInterval(timer);
var _ele = document.getElementById("test");
timer = setInterval(function(){
var _left = _ele.offsetLeft,
_speed = (target - _left)>0?Math.ceil((target - _left)/200):Math.floor((target - _left)/200);
if (_ele.offsetLeft == target){
if(WINDOW_WIDTH == target){
target = 0;
}else{
target = WINDOW_WIDTH;
}
clearInterval(timer);
};
_ele.style.left = _ele.offsetLeft+ _speed +'px';
},1)
}
}
</script>
</html>
大家可以看见
_speed = Math.ceil((target - _left)/200);
这里的速度除以了一个整数200,那么我们就要往上取整,因为不往上,可能_speed当为0的时候,其实运动物体还没有到达最终的目的,如果200-199 = 1 还差1像素,1像素/200 = 0.005 那么只有往上取值(Math.ceil()),如果往下取值(Math.floor),那么物体悠久不可能到达200像素这个距离。
那什么情况使用floor呢?当_speed相减的时候就用_speed = Math.floor((target - _left)/200),因为可能这个物体网往回走了,那么就用Math.floor(), 比如 0-1 = -1, -1/200 = -0.005 ,那么我们只能取-1,不然物体永久回不到原点。