jQuery 滚动不适用于锚点

jQuery scrolling does not work with anchor

本文关键字:适用于 不适用 滚动 jQuery      更新时间:2023-09-26

我想将页面滚动到锚链接。我使用以下代码:

$('a').click(function(){
        $('html, body').animate({
            scrollTop: $( $(this).attr('href') ).offset().top
        }, 400);
        return false;
    });

如果我有这样的网址,它可以正常工作:

<a href="#comments">Comments</a>

但是,问题是通过在当前 url 的末尾添加 # 来自动生成 url,因此它将是:

<a href="http://example/sth/#comments">Comments</a>

在这种情况下,它不起作用。我无法更改 URL 的标记,如何修复 jQuery 以使用此类 url?

您可以读取锚点的 hash 属性,而不是它的href

$('a').click(function(){
    $('html, body').animate({
        scrollTop: $(this.hash).offset().top
    }, 400);
    return false;
});

http://jsfiddle.net/KL5uw/

滚动到特定的锚标记,这只能用 HTML 完成

前任:

<a name="top"></a>  // where we have to reach
<a href="#top">last</a>     // we reach their by clicking on this we can also use an image, align in right

演示