jQuery 流畅的滚动锚导航

jQuery smooth scrolling anchor navigation

我的网站顶部有一个基于列表的导航,它是一个单页网站,因此 href 是页面上各个部分的锚点。我用过这段代码:jQuery smooth scroll positioning doesn't work

导航:

<nav>
   <ul class="navigation">
      <li class="navigation"><a class="scroll" href="#about-me">about me</a>
      </li>
      <li class="navigation"><a class="scroll" href="#my-skills" >my skills</a>
      </li>
      <li class="navigation"><a class="scroll" href="#portfolio">portfolio</a>
      </li>
      <li class="navigation"><a class="scroll" href="#contact">contact</a>
      </li>    
   </ul>
</nav>

Section/div:

<section id="contact"> <!---->
    <div class="panel" id="contact">
        <h2>Contact</h2>
    </div>
</section> <!---->

Javascript 使用:

<script type="text/javascript">
$(document).ready(function(){
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();

        var target = this.hash;
        $target = $(target);

        $('html, body').stop().animate({
            'scrollTop':  parseInt($target.offset().top,10);
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});
</script>

锚点有效并跳转到该部分,但没有滚动?

试试这个代码:

 <script type="text/javascript">
    $(document).ready(function(){
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);
        var scroll;

        if($(window).scrollTop()==0){
            scroll =  ($target.offset().top) - 160
        }else{
            scroll =  ($target.offset().top) - 60
        }
        $('html, body').stop().animate({
            'scrollTop': scroll
        }, 900, 'swing', function () {
            //window.location.hash = target;
        });
    });
});
</script>

你的代码有几个问题:

  • You haven't closed your lis properly
  • You have same ids for section and div which is invalid
<section id="contact"> <!---->
    <div class="panel" id="contact">

所以纠正上述错误我想在你的 JS 中再添加一个更改,即:

  • No need to add parseInt to scrollTop. You can directly go with the offset().top

DEMO

$(document).ready(function(){
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();
        var target = this.hash;
        $target = $(target);
        $('html, body').stop().animate({
            'scrollTop':  $target.offset().top //no need of parseInt here
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});