您的位置:首页 > 其它

封装缓动动画函数增加回调函数

2018-03-29 15:53 393 查看
<!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.onclick=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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: