jQuery滚动到Div

Chr*_*her 69 html jquery

我正在创建一个FAQ页面,并在顶部有按钮跳转到一个类别(它跳转到p我用作类别标签的标签,例如<p id="general">我的常规类别).我不想直接跳到类别,而是想添加滚动效果.我想要像http://www.dynamicdrive.com/dynamicindex3/scrolltop.htm那样滚动到我页面的所需部分.该链接是一个脚本,它以一个很好的滚动效果进入页面顶部.我需要类似的东西滚动到我链接的地方.例如,如果我想要一个misc.类别,我希望能够拥有<a href="#misc">Miscellaneous</a>并滚动到页面的该部分.

小智 115

这是经常需要移动身体和HTML对象在一起.

$('html,body').animate({
   scrollTop: $("#divToBeScrolledTo").offset().top
});
Run Code Online (Sandbox Code Playgroud)

ShiftyThomas是对的:

$("#divToBeScrolledTo").offset().top + 10 // +10 (pixels) reduces the margin.
Run Code Online (Sandbox Code Playgroud)

所以增加保证金使用:

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

  • 这里没有分号`.offset().top;` (19认同)

Far*_*den 90

$(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;
      }
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

查看此链接:http://css-tricks.com/snippets/jquery/smooth-scrolling/进行演示,之前我已经使用过,它运行得非常好.

  • 伙计们,我的(相关但不公正的投票)问题呢?http://stackoverflow.com/questions/28400107/jquery-bring-a-div-into-viewport也许您会有一些见解? (2认同)

Guf*_*ffa 28

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

$(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();
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 一般的想法。`$('a[href^=#]')` 是什么意思?那么`$('a[name='+name+']')`呢?另外,你是怎么想到要这样做的?我也想学学:) (2认同)

Jim*_*med 27

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

var position = $("div").position();
scroll(0,position.top);
Run Code Online (Sandbox Code Playgroud)


Sto*_*oic 9

如果链接元素是:

<a id="misc" href="#misc">Miscellaneous</a>
Run Code Online (Sandbox Code Playgroud)

杂项类别受以下内容的限制:

<p id="miscCategory" name="misc">....</p>
Run Code Online (Sandbox Code Playgroud)

你可以使用jQuery来实现所需的效果:

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

据我记得正确..(但是,我还没有测试它并从内存中写出来)

  • &lt;script type="text/javascript"&gt; $("#misc").click(function() { $("body").animate({scrollTop: $("#miscCategory").offset().top} ); }); &lt;/脚本&gt; (2认同)