我想使用平滑滚动转到我主页上的锚点。我使用下面的jQuery代码:
$(document).ready(function(){
$('a').click(function(){
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 1000);
return false;
});
});这是HTML代码:
<div id="menu">
<div id="menu-contain">
<ul>
<li><a class="home" href="#">Home</a></li>
<li><a class="about" href="#about">About</a></li>
<li><a class="projects" href="#projects">Projects</a></li>
<li><a class="contact" href="#contact">Contact</a></li>
</ul>
</div>
</div>这对除第一个锚之外的每个锚都很有效。如果我查看控制台,如果我单击第一个链接,则会出现错误:
Cannot read property 'top' of undefined我找到了很多关于这个错误的线索,但我没有找到适合我的解决方案。
感谢您的建议:)
发布于 2014-02-23 10:08:24
在使用目标元素之前,请检查它是否存在:
$('a').click(function(){
var $target = $($.attr(this, 'href'));
if ( ! $target.length ) return;
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 1000);
return false;
});你也应该在那里缓存你的选择器。See this thread for more details。
https://stackoverflow.com/questions/21963247
复制相似问题