2017-06-02 146 views
0

我使用最新評論here中的jQuery代碼片段。在用戶點擊選項卡時,如何避免第二種情況下的這種行爲?如何避免在某些內部鏈接上平滑滾動?

GOOD (it's working as it should): 
<a href="#schedule">Schedule</a> 

BAD (scrolls to the top of the page, which I dont want): 
<a class="nav-link" data-toggle="tab" href="#tour" role="tab">TOUR</a> 

<script> 
$('a[href*="#"]:not([href="#"])').click(function() { 
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { 
     var $target = $(this.hash); 
     $target = $target.length ? $target : $('[name=' + this.hash.slice(1) +']'); 

     if ($target.length) { 
     var baseMinScrollTime = 500, 
      baseMaxScrollTime = 900; 

     var docHeight = $(document).height(), 
      triggerTop = $(this).offset().top, 
      targetTop = $target.offset().top; 

     var scrollProportion = (targetTop - triggerTop)/docHeight, 
      relativeTime = ((baseMaxScrollTime - baseMinScrollTime) * scrollProportion) + baseMinScrollTime, 
      // Create inverse relationship (quicker the further we scroll) 
      scrollTime = -1 * (1 - relativeTime); 

     $('html, body').animate({ 
      scrollTop: targetTop - 10 
     }, scrollTime); 
     return false; 
     } 
    } 
    }); 
</script> 

回答

0

您可以提到,要避免在.not部分從您的代碼鏈接:

例如,如果你想避免命名爲「家」的鏈接,然後使用:

$('a[href*="#"]') 
:not('[href="#home"]') 
:not('[href="#anotherLinkToSkip"]') 
:not('[href="#yetAnother"]').click(function(){ 
     //your logic here 
}) 

:not幫助您選擇之前指定的所有內容,同時排除什麼在它之後被指定。您可以附加更多not塊以指定更多要排除的元素。更多信息here

+0

謝謝!我如何傳遞多個鏈接:#home,#one,#two,#three? – Jake

+0

更新了我的答案。它現在應該適合你 –