【问题标题】:Link to anchor on another page with smooth scrolling通过平滑滚动链接到另一个页面上的锚点
【发布时间】:2018-12-25 22:34:36
【问题描述】:

我已经搜索了这个答案的高低,但似乎找不到它。

我在主页上有锚点,顶部菜单中的链接可以滚动到它们。

这在主页上效果很好,但在子页面上却不起作用。

下面是我的代码:

$(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() 行可以使它们起作用。但它停止了漂亮的平滑滚动效果。

这里可以改变什么,以便我可以点击子页面上的锚链接,这些链接可以流畅地滚动到主页上的锚部分?

【问题讨论】:

  • 您所说的subpage是指另一个页面吗?如果是这样,通过在另一个页面上平滑滚动,您是否希望页面加载到顶部并平滑滚动到锚点?可以澄清这些点以获得更及时的答案。希望如此。

标签: javascript jquery anchor smooth-scrolling


【解决方案1】:

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

【讨论】:

  • 哇,太完美了!像魅力一样工作!非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2022-11-13
  • 2017-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-19
相关资源
最近更新 更多