1.三个函数
Math.ceil() 向上取整
Math.floor() 向下取整
Math.round() 四舍五入
2.缓动动画原理
盒子位置=盒子本身位置+(目标位置-盒子本身位置)/10
offsetLeft取值本身会四舍五入
3.缓动动画封装
封装模块
function animate(ele,target){
clearInterval(ele.timer);
ele.timer=setInterval(function(){
var step=(target-ele.offsetLeft)/10;
step=step>0?Math.ceil(step):Math.floor(step);
ele.style.left=ele.offsetLeft+step+"px";
if(Math.abs(target-ele.offsetLeft)<=Math.abs(step)){
ele.style.left=target+"px";
clearInterval(ele.timer);
}
},30)
}
案例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
div{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 0;
}
</style>
</head>
<body>
<button>运动到200</button>
<button>运动到400</button>
<div></div>
<script>
var btn=document.getElementsByTagName("button");
var div=document.getElementsByTagName("div")[0];
btn[0].onclick=function(){
animate(div,200);
}
btn[1].onclick=function(){
animate(div,400);
}
//缓动动画封装
function animate(ele,target){
clearInterval(ele.timer);
ele.timer=setInterval(function(){
var step=(target-ele.offsetLeft)/10;
step=step>0?Math.ceil(step):Math.floor(step);
ele.style.left=ele.offsetLeft+step+"px";
if(Math.abs(target-ele.offsetLeft)<=Math.abs(step)){
ele.style.left=target+"px";
clearInterval(ele.timer);
}
},30)
}
</script>
</body>
</html>