javascript - jQuery 滚动不适用于 anchor

标签 javascript jquery html

我想将页面滚动到 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;
});

http://jsfiddle.net/KL5uw/

关于javascript - jQuery 滚动不适用于 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19292234/

相关文章:

javascript - d3 - mouseover 和 mouseout 事件无法正常工作

javascript - 如何使用json从php页面获取两个或多个数组数据到javascript

javascript - 将嵌套数组、对象和属性左连接到一个平面表中

jquery - 如何将ajax的成功函数的结果与字符串进行比较

html - CSS:不能将两个div放在一起

html - ion-col 中的嵌套 div,100% 高度在 IOS 中不起作用

javascript - 在 jquery 移动应用程序中本地安全地存储用户密码

javascript - this.constructor.SomeVarible 与 OOP JS 中的 this.SomeVarible

jquery - anchor 链接在 Iphones/iOS 设备中不可点击

CSS 没有链接到 HTML