链接以平滑滚动到另一个页面上

时间:2018-07-18 06:08:20

标签: javascript jquery anchor 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()行可使它们正常工作。但这会停止流畅的滚动效果。

可以在此处进行哪些更改,以便在子页面上单击锚点链接,从而平滑地滚动到首页的锚点部分?

1 个答案:

答案 0 :(得分:1)

滚动后使用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
  });
});
相关问题