问答详情
源自:2-1 JS速度动画

方块来回抽动,求解答

<div class="hide" id="hide"><div class="hover" id="hover"></div></div>
<style>
  * {margin: 0; padding: 0; }
  .hide {height: 500px; width: 500px; background-color: red; position: absolute; left: -500px; }
  .hover {height: 50px; width: 50px; background-color: blue; position: relative; top: 225px; left: 500px; }
</style>

<script>
  var hide=document.getElementById('hide');
  var hover=document.getElementById('hover');
  var timer=null;
  var startMove=function() {
    clearInterval(timer);
    timer=setInterval(function(){
              if(hide.offsetLeft<0){
                hide.style.left=hide.offsetLeft+10+'px'
              }else{
                clearInterval(timer)
              }},30
    )
  };

  var endMove=function() {
    timer=setInterval(function(){
              if(hide.offsetLeft>-500){
                hide.style.left=hide.offsetLeft-10+'px'
              }else{
                clearInterval(timer)
              }},30
    )
  };

  hover.onmouseover=function() {
    startMove();
  };

  hover.onmouseout=function() {
    endMove();
  };

</script>


提问者:懒人一只 2016-03-11 15:10

个回答

  • Joeh
    2016-03-11 17:11:48
    已采纳

    hide.offsetLeft<0,hide.offsetLeft>-500


  • Joeh
    2016-03-11 17:30:10

    onmouseover和onmouseout绑定在hide元素上

  • Joeh
    2016-03-11 17:05:59

    hide.offsetLeft>-500