为什么我的timer设置在function move()之内方块就会来来回回的,但是设置成全局变量就没事了呢?下面是我的代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
*{margin: 0;
padding: 0}
#div{
position:relative;
left: -200px;
width: 200px;
height: 100px;
margin:10px 0;
background: red;
}
#div span{
width: 20px;
height: 50px;
background:blue;
position: absolute;
left: 200px;
top:75px;
}
</style>
<script>
window.onload=function(){
var div=document.getElementById('div');
div.onmouseover=function(){
move(0);
}
div.onmouseout=function(){
move(-200);
}
}
var timer=null;
function move(iTarget){
clearInterval(timer);
var div=document.getElementById('div');
timer=setInterval(function(){
if(div.offsetLeft==iTarget){
clearInterval(timer);
}else{
if(div.offsetLeft<iTarget){
div.style.left=div.offsetLeft+50+'px';
}else if(div.offsetLeft>iTarget){
div.style.left=div.offsetLeft-50+'px';
}
}
},100);
}
</script>
</head>
<body>
<div id="div">
<span id="span">分享</span>
</div>
</body>
</html>