如何避免在某些内部链接上平滑滚动?

时间:2017-06-02 15:31:05

标签: jquery bootstrap-4 smooth-scrolling

我使用了最新评论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>

1 个答案:

答案 0 :(得分:0)

您可以在代码的.not部分中提及您要避免的链接:

例如,如果您想避免名为“home”的链接,请使用:

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

:not可帮助您选择之前指定的所有内容,同时排除其后指定的内容。您可以添加更多not块以指定要排除的更多元素。更多信息here