0

嗨,我编写了一些代码,在单击后将页面滚动到一个元素,但在平滑滚动之前它会跳转到页面顶部。有人可以解释一下我做错了什么吗?

这是脚本

$('a[href*="#"]').click(function(e){
        e.preventDefault();
    if($(this).attr('href') == '#') {
       $('html, body').animate({
        scrollTop: $('body').offset().top
       }, 1000);
       window.location.hash = '';
    } else {
        $('html, body').animate({
            scrollTop: $( $.attr(this, 'href') ).offset().top - $(this).height()
        }, 1000);   
        window.location.hash = $(this).attr('href');
    }
        return false;
});

并告诉我在哪里可以学习 JS :) 请

4

2 回答 2

0

本教程和演示展示了如何实现这一目标。看看它。http://css-tricks.com/snippets/jquery/smooth-scrolling/

于 2013-08-01T06:16:36.900 回答
0

这是菜单的html

<div class="menu">
  <div class="top">
    <ul class="menu_list">
      <li><a href="#">Start</a></li>
      <li><a href="#o_nas">About</a></li>
      <li><a  href="#services">Services</a></li>
      <li><a href="#portfolio">Portfolio</a></li>
      <li><a href="#contact">Contact</a></li>
     </ul>
  </div>
</div>

这是菜单的修改脚本

//menu smooth scroll to element
    $('a[href^="#"]').on('click',function(e){
        $target = $(this).attr('href');
       e.preventDefault();
        $('.active').removeClass('active');
        $(this).addClass('active');
        if($(this).attr('href') == '#') {

           $('html, body').stop().animate({
            scrollTop: $('body').offset().top
           }, 1000, function(){location.hash = $target;});
        } else {
            $('html, body').stop().animate({
                scrollTop: $($target).offset().top + 57 - $('.menu').height() 
//this is important to add + height of menu holder div in my case it's 57 this removes jump effect in firefox
            }, 1000,function(){location.hash = $target});

        }
        return false;
    });

我已经解决了我的问题,就是这样,上面的代码对我来说很完美,我把它放在这里供像我这样的其他程序员使用;)我们得到了具有 url 更改和平滑滚动效果的单页站点:P

于 2013-10-24T07:49:03.637 回答