我想将页面滚动到 anchor 链接。我正在使用以下代码:
$('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?
最佳答案
您可以读取 anchor 的 hash
属性,而不是它的 href
:
$('a').click(function(){
$('html, body').animate({
scrollTop: $(this.hash).offset().top
}, 400);
return false;
});
关于javascript - jQuery 滚动不适用于 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19292234/