<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style type="text/css">
div{
width: 100px;
height: 100px;
position: absolute;
top: 40px;
left: 20px;
background-color: pink;
}
</style>
<script type="text/javascript">
window.onload=function(){
var btn=document.getElementById('btn');
var div=document.getElementById('div');
var num=0;
btn.onclick=function(){
doMove(div,'left',30,800,function(){
doMove(div,'top',30,600,function(){
doMove(div,'left',30,30,function(){
doMove(div,'top',30,40);
});
});
});
}
function doMove(obj,attr,dir,target,endFn){
dir=parseInt(getStyle(obj,attr))<target?dir:-dir;
clearInterval(obj.timer);
obj.timer=setInterval(function(){
num=parseInt(getStyle(obj,attr))+dir;
if(num>target&&dir>0||num<target&&dir<0){
num=target;
}
obj.style[attr]=num+'px';
if(num==target){
clearInterval(obj.timer);
endFn&&endFn();
}
},30);
}
function getStyle(obj,attr){
return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj)[attr];
}
}
</script>
<body>
<input id="btn" type="button" name="" value="走">
<div id="div"></div>
</body>
</html>
js的定时回调函数
最新推荐文章于 2023-06-21 08:34:02 发布