关于html:jQuery滚动到Div

jQuery Scroll to Div

我正在制作一个FAQ页面,并在顶部具有按钮以跳到一个类别(它跳到我用作类别标签的p标签,例如,我的常规类别为

)。
我想添加一个滚动效果,而不仅仅是跳到该类别。 我想要类似http://www.dynamicdrive.com/dynamicindex3/scrolltop.htm的内容,该内容可以滚动到页面的所需部分。 该链接是一个脚本,该脚本转到页面顶部,具有良好的滚动效果。 我需要类似的东西,可以滚动到我链接的位置。 例如,如果我想去其他地方。 类别,我希望能够拥有Miscellaneous并将其滚动到页面的该部分。


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

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

ShiftyThomas是正确的:

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

因此,要增加保证金的使用:

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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
$(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/以获取演示,我以前使用过它,并且效果很好。


这样,您就可以接管每个内部链接的单击并滚动到相应书签的位置:

1
2
3
4
5
6
7
8
$(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滚动:

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

如果链接元素是:

1
Miscellaneous

并且"杂类"类别受以下内容限制:

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

您可以使用jQuery达到预期的效果:

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

据我没记错的话..(尽管我还没有测试它并从内存中写入它)