根据 this question ,我使用了以下代码:
$("a.smooth-scroll").click(function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 1000);
});
我的 HTML 看起来像这样:
<a href="#product-list" class="btn btn-default smooth-scroll"><span class="fa fa-list-ul"></span>Full Product List</a>
以及相应的链接:
<a name="product-list"></a>
但我收到一个 javascript 错误:
shop.js:8 Uncaught TypeError: 无法读取未定义的属性“top”
这是为什么?
最佳答案
$.attr(this, 'href')
(或者,$(this).attr('href')
)您的链接将返回字符串 #product-list
。
运行 $('#product-list')
时,它会查找 id 为 product-list
的元素,在此case 不返回任何元素。尝试获取空集的 offset()
会返回 undefined
。您无法访问 undefined
的属性,这就是您的代码无法正常工作的原因。
或者,我会考虑使用此处找到的解决方案 - https://css-tricks.com/snippets/jquery/smooth-scrolling/
关于jquery - 使用 <a href ='#' > 平滑滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36180885/