2013-08-01 42 views
0

您好我已经写了一些代码,滚动页面后,点击一个元素,但在平滑滚动之前,跳转到页面的顶部。有人能解释我做错了什么吗?jQuery - 平滑滚动到div

这是脚本

$('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 :)请

+0

Go thro'以下链接为学习和Masterin g JS :) http://stackoverflow.com/questions/2687566/learning-javascript-in-one-weekend http://stackoverflow.com/questions/11246/best-resources-to-learn-javascript –

+0

将此行放入'window.location.hash ='''是什么原因?你有没有尝试没有这条线? – anu

+0

是的,我已经尝试了很多配置,但它仍然“跳跃”在Firefox中 – arclite

回答

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; 
    }); 

我已经解决了我的问题,这是它,上面的代码完美的作品对我我把它放在这里给像我这样的其他程序员;),我们得到了网页更改和平滑滚动效果的单页网站:P

0

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

+0

这不是我正在寻找我的脚本工程伟大的铬,但在Firefox中它无法正常工作。网址正在改变,但在滚动后它跳转到元素,点击后跳转到网站的顶部 – arclite