<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>缓存动画的封装</title>
<style>
*{
margin: 0;
padding: 0;
}
div{
width: 200px;
height: 200px;
position: absolute;
background-color: blue;
}
</style>
<script>
window.onload=function(){
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);
}
//封装animate函数
function animate(ele,target){
//实用定时器前先清除定时器
clearInterval(ele.timer);
//设置定时器
ele.timer=setInterval(function(){
//除以10是为了取得黄金比例,事先约定俗成的
//步长应该是越来越小的,缓动的算法。
var stept=(target-ele.offsetLeft)/10;
stept=stept>0?Math.ceil(stept):Math.floor(stept);
//目标位置=当前位置+步长
ele.style.left=ele.offsetLeft+stept+"px";
//用于判断什么时候清除定时器
if(Math.abs(target-ele.offsetLeft)<=Math.abs(stept)){
ele.style.left=target+"px";
setInterval(ele.timer);
};
},30)
}
}
</script>
</head>
<body>
<button>向前运动200</button>
<button>向前运动400</button>
<div></div>
</body>
</html>
缓存动画
最新推荐文章于 2022-09-18 16:59:02 发布