滚动动画只播放一次

时间:2013-07-12 10:40:56

标签: jquery animation scroll

滚动#徽标和#导航移动时。我想让动画只播放一次但是,我怎样才能最好地实现?

    var viewportWidth = $(window).width();
    var viewportHeight = $(window).height();
    var contentHeight = $('#content').height();
    var footerHeight = $('#footer').height();


    var newSize = viewportHeight - footerHeight + 50;

    var $navigation = $('#navigation');
    var $logo = $('#logo'); 
    var noRun = 0
    var $win = $(window).scroll(function() {
        $navigation.animate({
          top: newSize}, 1500, function() {
          $('#navigation .active').removeClass('active');
          $('#navigation .current').addClass('active');

          console.log('animation 1 finished');


          });
        $logo.animate({
          top: 100}, 1500, function() {
          console.log('animation 2 finished');


          });
    });

1 个答案:

答案 0 :(得分:0)

播放动画后,从$(窗口)取消绑定滚动事件监听器,以使动画永远不会被滚动事件再次播放。

var $win = $(window).scroll(function() {

    $navigation.animate({
      top: newSize}, 1500, function() {
      $('#navigation .active').removeClass('active');
      $('#navigation .current').addClass('active');
      console.log('animation 1 finished');
      });

    $logo.animate({
      top: 100}, 1500, function() {
      console.log('animation 2 finished');
    });

    $(window).off('scroll');
});

<强>更新

如果您使用的jQuery版本低于1.7,请使用unbind代替off

<强>的jsfiddle

http://jsfiddle.net/XghCY/1/

<div style="height: 2000px;"></div>

$(window).scroll(function() {
    alert('scroll event is triggered!');
    $(window).off('scroll');
});