在另一页上使用平滑滚动链接到锚点

4

我已经费尽心思寻找答案,但似乎找不到。

在主页上我有带有链接的锚点,可以滚动到它们的位置。

这在主页上很好用,但在子页面上却不能正常工作。

以下是我的代码:

$(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()这一行可以使它们起作用。但是这会停止漂亮的平滑滚动效果。
有什么方法可以改变这里的内容,使我可以点击子页面上的锚链接,然后平滑滚动到主页上的锚点部分?

1
你所说的“subpage”是指另一个页面吗?如果是的话,“在另一个页面上平滑滚动”,您是否想要像页面加载到顶部并平滑地滚动到锚点这样的效果?这些细节可以澄清以便更快地得到答案。希望如此。 - vahdet
1个回答

4
在滚动后使用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
  });
});

哇,太完美了!像魔法一样顺利!非常感谢你的帮助!! - Kiki

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接