缓冲运动:(含义)
比如列车运行(天津站——北京站),中途一直保持匀速运动,临近站点时减速直到停。
假设目标值为300px,那么target就是300px
越接近目标值越慢,但是并没有到300px这个点,到292.8px
注意:像素px不能有小数,因此刚才的24.3是不对的,需要归置一下
先打印一下speed,由于鼠标移入是正值,移出是负值
因此可以做一下判断:如果speed>0
这时候它停止就是300px
那么如果speed<0,就会在0px停止
对if判断语句进行优化:(改为三目运算符更好)
完整代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style>
*{margin: 0;padding: 0;}
#box{
width: 200px;
height: 200px;
background: lightcoral;
position: absolute;
left: 0;
top: 0;
}
</style>
<body>
<div id="box"></div>
<script>
var box = document. getElementById("box");
//移入
box.onmouseover = function(){
animate(box,300); //传入参数
}
//移出
box.onmouseout = function(){
animate(box,0);
}
var timer = null;
function animate(dom,target){
clearInterval(timer);
timer = setInterval(function(){
var speed = (target-dom.offsetLeft)/10;
/*dom.offsetLeft
0(开始)——> 300(停止)
targct-dom.offsetLeft 300/10=30
……
target-30 270/10=27
300-57 243/10=24.3
*/
//console.log(speed);
/*if(speed>0){ //if判断语句
speed = Math.ceil(speed);
}else{
speed = Math.floor(speed);
}
*/
speed = speed>0 ?Math.ceil(speed):Math.floor(speed); //优化
if(target == dom.offsetLeft){
//停止定时器
clearInterval(timer);
}else{
dom.style.left = dom.offsetLeft + speed +"px";
}
},30)
}
</script>
</body>
</html>