如何解决未捕获的类型错误:无法读取未定义的属性'top'



>我有一个页面网站。 我用JS添加了平滑滚动。

$(document).ready(function(){
$("li > a").on('click', function(e) {
if (this.hash !== "") {
e.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
window.location.hash = hash;
});
}
});
});

这是我的导航HTML代码:

<li class="{{ slug == '/' ? 'active' : '' }}"><a href="#home">HOME</a></li>
<li class="{{ slug == '/about' ? 'active' : '' }}"><a href="#about">ABOUT</a></li>
<li class="{{ slug == '/blog' ? 'active' : '' }}"><a href="#blog">BLOG</a></li>

但是当我转到另一个页面(如博客(时,单击导航再次转到一页时出现错误顶部。 我错过了什么吗?

我希望当你得到它们时,你的哈希值会如此"#about"和"#home"#blog"。

plaease使用你的哈希值而不带"#",因为你的ID没有"#"对吗?

确保在页面中放置了具有正确id的相关元素:

$(document).ready(function(){
$("li > a").on('click', function(e) {
if (this.hash !== "") {
e.preventDefault();
var hash = this.hash;
if ($(hash).length > 0) {
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function() {
window.location.hash = hash;
});
}
}
});
});
ul {
position: fixed;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class=""><a href="#home">HOME</a></li>
<li class=""><a href="#about">ABOUT</a></li>
<li class=""><a href="#blog">BLOG</a></li>
</ul>
<div id="home" style="margin:500px 0;">
Home
</div>
<div id="about" style="margin:500px 0;">
About
</div>
<div id="blog" style="margin:500px 0;">
Blog
</div>

最新更新