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

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

有没有办法使滚动流畅?

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


当前回答

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

$('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

其他回答

要求jquery和动画锚标签与指定的名称而不是id,同时添加哈希到浏览器url。还修复了大多数jquery答案中#符号没有带转义反斜杠前缀的错误。返回按钮,不幸的是,不能正确地导航回以前的哈希链接…

$('a[href*=\\#]').click(function (event)
{
    let hashValue = $(this).attr('href');
    let name = hashValue.substring(1);
    let target = $('[name="' + name + '"]');
    $('html, body').animate({ scrollTop: target.offset().top }, 500);
    event.preventDefault();
    history.pushState(null, null, hashValue);
});

CSS3的新热点。这比本页列出的所有方法都要简单得多,而且不需要Javascript。只需输入下面的代码到你的css和所有的链接指向你自己的页面内的位置将有一个平滑的滚动动画。

html{scroll-behavior:smooth}

之后,任何指向div的链接都将平滑地滑到这些部分。

<a href="#section">Section1</a>

编辑:对于那些对上面的一个标签感到困惑的人。基本上它是一个可点击的链接。然后你可以在你的网页的某个地方有另一个div标签

<div id="section">content</div>

在这种情况下,a链接将是可点击的,并将转到#section是什么,在这种情况下,它是我们称为section的div。

顺便说一句,我花了好几个小时才让它工作。在一些晦涩的评论区找到了解决方案。它是错误的,不会工作在一些标签。对身体不起作用。当我把它放在CSS文件中的html{}中时,它终于工作了。

以下是我为多个链接和锚点实现的解决方案,用于平滑滚动:

http://www.adriantomic.se/development/jquery-localscroll-tutorial/ 如果你在导航div中设置了导航链接,并声明了这样的结构:

<a href = "#destinationA">

和你相应的锚标签目的地如下:

<a id = "destinationA">

然后把这个加载到文档的头部:

    <!-- Load jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

<!-- Load ScrollTo -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.scrollTo-1.4.2-min.js"></script>

<!-- Load LocalScroll -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.localscroll-1.2.7-min.js"></script>

<script type = "text/javascript">
 $(document).ready(function()
    {
        // Scroll the whole document
        $('#menuBox').localScroll({
           target:'#content'
        });
    });
</script>

感谢@Adriantomic

使用JQuery:

$('a[href*=#]').click(function(){
  $('html, body').animate({
    scrollTop: $( $.attr(this, 'href') ).offset().top
  }, 500);
  return false;
});

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

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

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

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