2

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

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

4

2 回答 2

3

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

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

http://jsfiddle.net/KL5uw/

于 2013-10-10T09:43:32.663 回答
-1

滚动到特定的锚标记,这可以通过 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

演示

于 2013-10-10T09:46:44.480 回答