<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<style type="text/css">
#dv{
width:200px;
height: 100px;
background-color: gray;
position: absolute;
}
</style>
</head>
<body>
<input type="button" value="移动" id="btn" name="">
<div id="dv"></div>
<script type="text/javascript">
var obtn=document.getElementById("btn");
var odv=document.getElementById("dv");
json={"width":200,"height":300,"top":150,"left":500};
json1={"width":100,"height":400,"top":350,"left":200};
obtn.οnclick=function(){
animate(odv,json,function(){animate(odv,json1)});
};
function animate(element,json,fn){
clearInterval(element.timer);
element.timer=setInterval(
function(){
var flag=true;
for(var attr in json){
var current=parseInt(getStyle(element,attr)); //这个取得的是字符串 需要parseInt
var target=json[attr];
var step=(target-current)/10;
step=step>0?Math.ceil(step):Math.floor(step);
current+=step;
element.style[attr]=current+"px";
if(current!=target){flag=false;}
}
if(flag){
clearInterval(element.timer);
if(fn)
{fn();}
}
},20);
}
function getStyle(element,attr){
return window.getComputedStyle?window.getComputedStyle(element,null)[attr]:element.currentStyle[attr]; //第一个谷歌火狐第二个IE
}
</script>
</body>
</html>
封装缓动动画函数增加回调函数
最新推荐文章于 2021-04-12 20:09:06 发布