天天看點

關于setInterval的一個例子

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<style type="text/css">
*{margin: ;padding: p}
#div1{
  width: px;
  height: px;
  background: red;
  position: relative;
  left :-px;
  top:;}
#div1 span{
  width: px;
  height: px;
  background: blue;
  position: absolute;
  left:px;
  top:px;
}
</style>
<script type="text/javascript">
window.onload=function(){
  var oDiv=document.getElementById('div1');
  oDiv.onmouseover=function(){
    startMove()
  }
  oDiv.onmouseout=function(){
    startMove(-)
  }
}

var timer=null;
var startMove=function(iTarget){
  var oDiv=document.getElementById('div1')
  var speed=
  clearInterval(timer);
  var timer=setInterval(function(){//為什麼這個地方加一個var,行為會變得非常怪,哪裡錯了呢。。

    if(oDiv.offsetLeft>iTarget){
      speed=-
    }else{
      speed=
    }
    if(oDiv.offsetLeft==iTarget){
      clearInterval(timer)
    }
    else{
    oDiv.style.left=oDiv.offsetLeft+speed+'px'
    }
  },)
}
</script>
<body>
  <div id="div1"><span id="share">分享</span></div>
</body>
</html>
           

繼續閱讀