<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
div{
width:200px;
height: 100px;
background-color: pink;
margin-top: 20px;
position:absolute;
}
</style>
</head>
<body>
<input type="button" id="btn1" value="移动到400px" name="">
<input type="button" id="btn2" value="移动到800px" name="">
<div id="dv"> </div>
<script type="text/javascript">
var obtn1=document.getElementById('btn1');
var obtn2=document.getElementById('btn2');
var odv=document.getElementById('dv');
obtn1.οnclick=function(){ animate(odv,400)};
obtn2.οnclick=function(){ animate(odv,800)};
function animate(element,target)
{ clearInterval(element.timer);
element.timer=setInterval(function(){
var current=element.offsetLeft;
var step=10;
step=current<target?step:-step;
current+=step;
if(Math.abs(current-target)>Math.abs(step))
{
element.style.left=current+"px";
}
else
{
clearInterval(element.timer);
element.style.left=target+"px";
}
},20);
}
</script>
</body>
</html>
定时器---移动元素div
最新推荐文章于 2021-03-20 22:20:14 发布