jQuery平滑滚动锚导航

时间:2015-08-05 12:14:22

标签: jquery navigation anchor smooth-scrolling

我的网站顶部有一个基于列表的导航,它是一个单页网站,因此a hrefs是页面上各个部分的锚点。我已使用此代码: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>

节/ 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>

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

2 个答案:

答案 0 :(得分:7)

您的代码中存在一些问题:

  
      
  • 您尚未正确关闭li
  •   
  • id sectiondiv无效
  •   
<section id="contact"> <!---->
    <div class="panel" id="contact">

因此纠正上述错误我想在您的 JS 中添加一项更改:

  
      
  • 无需将parseInt添加到scrollTop。您可以直接使用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;
        });
    });
});

答案 1 :(得分:2)

试试这段代码:

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