2

我有一个页面的网站。我用js添加了smoothscroll。

$(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>

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

4

2 回答 2

0

确保您在页面中放置了正确的相关元素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>

于 2018-08-16T04:17:14.863 回答
0

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

请使用不带“#”的哈希,因为您的 id 不带“#”,对吗?

于 2018-08-16T04:20:04.753 回答