【发布时间】:2018-06-07 04:52:57
【问题描述】:
我正在寻找如何为 example.com/subpage#anchor 等链接添加平滑滚动的方法。
我正在尝试使用此代码
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
但它不适用于 example.com/subpage#anchor
【问题讨论】:
-
$.attr似乎不是 api 中的方法,只有$.fn.attr是。尝试改用$(this.getAttribute('href'))。 -
什么都没有改变,它仍然不起作用,但现在我得到一个错误 TypeError: $ is not a function
-
我打算给出一个显示 getAttribute() 的答案,但您的逻辑似乎可以正常工作。
标签: javascript jquery scroll