2016-10-13 71 views
0

我有觸發滾動到已被點擊,你可以看到下面的ID這個非常簡單的單擊事件:當這個被炒魷魚防止代碼,如果點擊事件已觸發被稱爲

$('.navigation-panel a').on('click', function() { 
    var id = $(this).attr('href'); 
    $('html, body').animate({ scrollTop: $(id).offset().top - 100 }, 1000); 
}); 

它也引發我的其他滾動事件,你可以在這裏看到:

$(window).scroll(function() { 
     var y = $(this).scrollTop(); 

     menu.each(function (event) { 
      if (y >= $($(this).attr('href')).offset().top - 100) { 
       menu.not(this).removeClass('active'); 
       $(this).addClass('active'); 
      } 
     }); 

    }); 

,我想回答的是我如何阻止如果點擊事件已經發生了正在執行第二腳本的問題?不過,我需要在點擊事件完成後觸發第二個腳本。

腳本必須分開,因爲第二個腳本對於用戶只是滾動而不是單擊以導航到頁面的不同部分很重要。

回答

5

單擊時不觸發事件處理程序的一種確定方法是臨時刪除事件處理程序,然後當動畫結束時再次附加事件處理程序並觸發它。

$(window).on('scroll', scroller); 

function scroller() { 
    var y = $(this).scrollTop(); 

    menu.each(function(event) { 
     if (y >= $($(this).attr('href')).offset().top - 100) { 
      menu.not(this).removeClass('active'); 
      $(this).addClass('active'); 
     } 
    }); 
} 

$('.navigation-panel a').on('click', function() { 
    var id = $(this).attr('href'); 

    $(window).off('scroll', scroller); 

    $('html, body').animate({ 
     scrollTop: $(id).offset().top - 100 
    }, 1000, function() { 
     $(window).on('scroll', scroller).trigger('scroll'); 
    }); 
}); 
+0

輝煌感謝 –

0

@ adeneo的方式可能是單個事件的方法做正確的事情,但你也可以使用一個全局標誌也需要這樣做:

var dontScroll = false; 

$('.navigation-panel a').on('click', function() { 
    var id = $(this).attr('href'); 
    dontScroll = true; 
    $('html, body').animate({ 
     scrollTop: $(id).offset().top - 100 
    }, { 
     duration: 1000, 
     complete: function(){ 
      dontScroll = false; 
     } 
    }); 
}); 

$(window).scroll(function() { 
    if(!dontScroll){ 
     var y = $(this).scrollTop(); 

     menu.each(function (event) { 
      if (y >= $($(this).attr('href')).offset().top - 100) { 
       menu.not(this).removeClass('active'); 
       $(this).addClass('active'); 
      } 
     }); 
    } 
});