2017-01-11 64 views
0

我有順利滾動JS從菜單項鍊接到頁面下方的錨點。從標籤中刪除平滑滾動

問題是,因爲我的頁面上使用了選項卡(使用#tabname)進行導航,所以在使用它們時也會嘗試滾動。

有沒有簡單的改變,我可以讓JS來阻止它在標籤上工作?

$(document).ready(function() { 
 
    // Add smooth scrolling to all links 
 
    $("a").on('click', function (event) { 
 

 
     // Make sure this.hash has a value before overriding default behavior 
 
     if (this.hash !== "") { 
 
      // Prevent default anchor click behavior 
 
      event.preventDefault(); 
 

 
      // Store hash 
 
      var hash = this.hash; 
 

 
      // Using jQuery's animate() method to add smooth page scroll 
 
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area 
 
      $('html, body').animate({ 
 
       scrollTop: $(hash).offset().top 
 
      }, 800, function() { 
 

 
       // Add hash (#) to URL when done scrolling (default click behavior) 
 
       window.location.hash = hash; 
 
      }); 
 
     } // End if 
 
    }); 
 
});

+0

更好的目標點擊元素 - >'$( 「A」)上('click'' < - 目標** **任何錨標記。 – Scott

回答

2

您可以爲錨元素選擇退出滾動行爲,例如的一種方式篩選出錨與data-no-scroll屬性:

<a href="#tab1" data-no-scroll>Tab1</a> 

$("a").not("[data-no-scroll]").click(function() { 
    ... 
});