Link 锚定在另一个页面上,滚动流畅

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.preventDefault & event.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
  });
});