jQuery"格斗"滚动效果点击链接后滚动滚动

时间:2018-03-03 00:32:01

标签: jquery scroll anchor

我在页面上应用了一个代码,以便在用户单击菜单项(锚标记)时平滑滚动到特定的div。单击导航菜单后,页面将根据需要运行到该位置。问题是它"坚持"那个地方的页面和jquery阻止我们像往常一样滚动到其他地方。

我把href和id放在我的div上,因为我说滚动效果正常,唯一奇怪的是,在它到达所需的位置之后,jquery阻止我向上或向下滚动。 / p>

这是JS代码:

$("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();

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

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

有人知道为什么会这样吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

这是旧文章,但这是您的问题的解决方案。如果用户使用滚动条,则需要jQuery .stop()函数来停止动画。

$(window).bind("mousewheel", function() {
$("html, body").stop();
});