簡體   English   中英

通過平滑滾動鏈接到另一頁上的錨點

[英]Link to anchor on another page with smooth scrolling

我已經搜索了這個答案的高低,但似乎無法找到它。

我在主頁上有錨點,頂部菜單中有鏈接滾動到它們。

這在主頁上很有用,但在子頁面上它不起作用。

以下是我的代碼:

$(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();
      event.stopPropagation();
      // 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
        }, 2000, function(){

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

到目前為止,我發現刪除event.preventDefault()行使它們工作。 但它會停止很好的平滑滾動效果。

這里可以改變什么,以便我可以點擊子頁面上的錨點鏈接,通過平滑滾動導致主頁上的錨點部分?

使用return false; 相反,滾動后,刪除event.preventDefaultevent.stopPropagation()

嘗試以下代碼:

$(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 !== "") {

      // 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
      }, 2000, function() {

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM