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 :)请

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

这是菜单的HTML

  

这是菜单的修改脚本

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