滚动时如何让循环动画暂停?

时间:2010-11-16 04:06:02

标签: jquery animation html hover

这是我到目前为止所管理的内容,但似乎没有人可以帮助我完成最后几个功能:

<script type='text/javascript''>
    $(document).ready(function () {     
        swing(); 
    });

    function swing() { //making the div swing
        $('#share').animate({right: '210px'}, 1000, function(){swingback()});

    }

    function swingback() { //making the div swing back
        $('#share').animate({right: '220px'}, 1000, function(){swing()});

    }

    $('#share').mouseenter(function() { // stop any animation if the mouse enters the div
        $(this).stop();


    }).mouseleave(function() { // continue animation once the mouse has left the div
        swingBack();

    });



</script>

2 个答案:

答案 0 :(得分:1)

// flag to help manage animation 
var resume = false;

$(document).ready(function(){
  swing();
});


function swing(v){
  // if animation was stopped mid-swing then resume
  var total = v ? 210-Math.abs(v): 210;

  $('#share').animate({
      right: '+=' + total + 'px'
  }, 1000, function(){
      resume = false;
      swingBack();
  });
}

function swingBack(){
  $('#share').animate({
    right: '0px'
  }, 1000, function(){
    resume = true
    swing();
  });
}

$('#share').bind({
  mouseenter: function(){
     $(this).stop();
  },
  mouseleave: function(){
    // get elements current position -- pass it to swing method for resume
    var v = parseInt($(this).css('right'), 0);

    if(resume)
      swing(v);
    else
      swingBack();  
  }
});

我在jsFiddle上创建了一个演示 - here

希望这有帮助

答案 1 :(得分:0)

感谢您的帮助,但我设法采取了不同的方式。 这看起来很奇妙,所以如果其他人发现自己也在问同样的问题,那就试试吧:)

<script type='text/javascript''>
    $(document).ready(function () {     

        var moving = true;

        swing();            

        function swing() {
            if(moving==true) {
                $('#share').animate({right: '210px'}, 1000, function(){swingback()});
            }
        }

        function swingback() { 
            if (moving==true) {             
                $('#share').animate({right: '220px'}, 1000, function(){swing()});
            }                   
        }

        $('#share').mouseenter(function() {
            moving = false;             
        });

        $('#share').mouseleave(function() {
            moving = true;
            swing();
        });     
    });

</script>