jQuery滚动到Div

我正在制作一个常见问题页面,并在顶部有button跳转到一个类别(它跳转到我用作类别标签的<p id="general">标签,例如我的常规类别的<p id="general"> )。 而不是只是跳到类别,我想添加滚动效果。 我想像http://www.dynamicdrive.com/dynamicindex3/scrolltop.htm滚动到我的网页的所需部分。 该链接是一个脚本,带有一个不错的滚动效果的页面顶部。 我需要类似的东西,将滚动到我链接到的地方。 例如,如果我想去混杂。 类别,我想只能够<a href="#misc">Miscellaneous</a> ,并让它滚动到该页面的该部分。

 $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); }); 

查看这个链接: http : //css-tricks.com/snippets/jquery/smooth-scrolling/对于一个演示,我以前使用它,它工作得很好。

通常需要将body和html对象一起移动。

 $('html,body').animate({ scrollTop: $("#divToBeScrolledTo").offset().top }); 

ShiftyThomas是对的:

 $("#divToBeScrolledTo").offset().top + 10 // +10 (pixels) reduces the margin. 

所以要增加保证金的使用:

 $("#divToBeScrolledTo").offset().top - 10 // -10 (pixels) would increase the margin between the top of your window and your element. 

像这样的东西可以让你接pipe每个内部链接的点击并滚动到相应书签的位置:

 $(function(){ $('a[href^=#]').click(function(e){ var name = $(this).attr('href').substr(1); var pos = $('a[name='+name+']').offset(); $('body').animate({ scrollTop: pos.top }); e.preventDefault(); }); }); 

可以使用JQuery位置函数来获取div的坐标,然后使用javascript滚动:

 var position = $("div").position(); scroll(0,position.top); 

如果链接元素是:

 <a id="misc" href="#misc">Miscellaneous</a> 

而其他类则被类似的东西包围着:

 <p id="miscCategory" name="misc">....</p> 

你可以使用jQuery来达到理想的效果:

 <script type="text/javascript"> $("#misc").click(function() { $("#miscCategory").animate({scrollTop: $("#miscCategory").offset().top}); }); </script> 

据我记得正确..(但是,我没有testing它,并从记忆中写道)

下面的脚本是一个适用于我的通用解决scheme。 这是基于从这个和其他线程拉出的想法。

当单击带有以“#”开头的href属性的链接时,它会平滑地滚动页面到指定的div。 只有“#”存在的地方,它会顺利地滚动到页面顶部。

 $('a[href^=#]').click(function(){ event.preventDefault(); var target = $(this).attr('href'); if (target == '#') $('html, body').animate({scrollTop : 0}, 600); else $('html, body').animate({ scrollTop: $(target).offset().top - 100 }, 600); }); 

例如,当上面的代码存在时,单击带有标签<a href="#">的链接以600的速度滚动到页面的顶部。单击带有标签<a href="#mydiv">的链接以600的速度滚动到<div id="mydiv"> 100px。随意更改这些数字。

我希望它有帮助!

我遇到了同样的情况。 看到一个使用这个例子: https : //github.com/flesler/jquery.scrollTo

我用它如下:

 $('#arrow_back').click(function () { $.scrollTo('#features_1', 1000, { easing: 'easeInOutExpo', offset: 0, 'axis': 'y' }); }); 

清洁解决scheme 为我工作!

您也可以使用'name'而不是'href'来获得更干净的url:

  $('a[name^=#]').click(function(){ var target = $(this).attr('name'); if (target == '#') $('html, body').animate({scrollTop : 0}, 600); else $('html, body').animate({ scrollTop: $(target).offset().top - 100 }, 600); });