我的页面上有几个超链接。一个常见问题,用户将阅读时,他们访问我的帮助部分。

使用锚链接,我可以使页面滚动到锚,并引导用户到那里。

有没有办法使滚动流畅?

但请注意,他使用的是自定义JavaScript库。也许jQuery提供了这样的功能?


当前回答

不需要任何js只是使用滚动行为:平滑的html标签就是这样

html{
scroll-behavior: smooth;
}

其他回答

这里已经有很多很好的答案——但是他们都忽略了一个事实,即空锚必须被排除在外。否则,只要单击空锚,这些脚本就会生成JavaScript错误。

在我看来,正确答案是这样的:

$('a[href*=\\#]:not([href$=\\#])').click(function() {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 500);
});

不需要任何js只是使用滚动行为:平滑的html标签就是这样

html{
scroll-behavior: smooth;
}

如果你在页面上有一个简单的按钮可以向下滚动到一个div,并且希望返回按钮通过跳到顶部来工作,只需添加以下代码:

$(window).on('hashchange', function(event) {
    if (event.target.location.hash=="") {
        window.scrollTo(0,0);
    }
});

这也可以扩展到跳转到不同的div,通过读取哈希值,并像Joseph Silbers的答案一样滚动。

我建议你编写这样的泛型代码:

$('a[href^="#"]').click(function(){

var the_id = $(this).attr("href");

    $('html, body').animate({
        scrollTop:$(the_id).offset().top
    }, 'slow');

return false;});

您可以在这里看到一篇非常好的文章:jquery- effect -smooth-scroll- pollution -fluide

经过测试和验证的代码

<script>
jQuery(document).ready(function(){
// Add smooth scrolling to all links
jQuery("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
  jQuery('html, body').animate({
    scrollTop: jQuery(hash).offset().top
  }, 800, function(){

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