如何使用jQuery滚动到特定项目?

278

我有一个带有垂直滚动条的大表格。我想使用jQuery/JavaScript滚动到此表格中的特定行。

是否有内置的方法可以实现这一点?

Here is a little example to play with.

div {
    width: 100px;
    height: 70px;
    border: 1px solid blue;
    overflow: auto;
}
<div>
    <table id="my_table">
        <tr id='row_1'><td>1</td></tr>
        <tr id='row_2'><td>2</td></tr>
        <tr id='row_3'><td>3</td></tr>
        <tr id='row_4'><td>4</td></tr>
        <tr id='row_5'><td>5</td></tr>
        <tr id='row_6'><td>6</td></tr>
        <tr id='row_7'><td>7</td></tr>
        <tr id='row_8'><td>8</td></tr>
        <tr id='row_9'><td>9</td></tr>
    </table>
</div>

13个回答

599

非常简单。不需要插件

var $container = $('div'),
    $scrollTo = $('#row_8');

$container.scrollTop(
    $scrollTo.offset().top - $container.offset().top + $container.scrollTop()
);

// Or you can animate the scrolling:
$container.animate({
    scrollTop: $scrollTo.offset().top - $container.offset().top + $container.scrollTop()
});​

这里有一个可用的示例

scrollTop的文档


4
如果容器有滚动条,你需要考虑scrollTop(滚动距离):scrollTo.offset().top - container.offset().top + container.scrollTop()。 - claviska
1
你可以使用 $(document).scrollTop(value) 滚动整个窗口 - 底层的 jQuery 代码会为您解决浏览器问题。 - Chris Moschini
7
如果你希望scrollTo不是在顶部而是居中显示:scrollTo.offset().top - container.offset().top + container.scrollTop() - (container.height()/2) - Mahn
8
element.scrollIntoView() - 这就是所需的。动画已标准化。请参见https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView。 - WickyNilliams
10
请注意,在代码块的末尾有一个“隐形”的字符。这个字符在Edge和Chrome中被认为是无效的。 - Attacktive
显示剩余8条评论

118

我意识到这并没有回答在容器中滚动的问题,但人们发现它很有用,所以:

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

我们选择html和body,因为文档滚动条可能在其中任何一个上,很难确定哪个。对于现代浏览器,您可以使用$(document.body)

或者,要转到页面顶部:

$('html,body').animate({scrollTop: 0});

或者不使用动画效果:

$(window).scrollTop(some_element.offset().top);

或者...

window.scrollTo(0, some_element.offset().top); // native equivalent (x, y)

你好 @infensus,你能给我一个可用的示例吗?我的代码似乎无法正常运行。我使用了以下代码:var section2=$('#section-2'); $('html,body').animate({scrollTop: section2.offset().top}); - anjelott1
看起来不错 - 你确定 section2 存在吗?执行 console.log(section2.length); 并确保它不为 0。稍后会举个例子。 - Dominic
为什么要使用 $('html,body')?他只需要在特定的容器中。被接受的答案对我更好。我有一个类似于所问问题的情况,你的答案对我没有用。 - Petroff
3
@Petroff 我写这个时候奇怪地没有注意到元素在一个滚动容器中。但我将保留我的回答,因为人们从Google搜索进来是要滚动页面的,这与问题标题有关。 - Dominic

32

我同意Kevin和其他人的观点,使用插件来做这件事是毫无意义的。

window.scrollTo(0, $("#element").offset().top);

对于应该非常简单的事情,我在网上寻找其他解决方案花费了很长时间,但这个简单的一行代码确切地做到了我所需的。 - Laurence Cope
3
请注意,这种方法适用于整个窗口。如果您想滚动具有overflow:scroll属性的内容,则此方法不起作用。 - Jeremy
我得试一下。我通过使用@lorddarq在上面回答的jQuery对“html,body”选择器进行了解决“单击某个元素时滚动到该元素”的问题。但是客户和同事说第一次单击时它不起作用,似乎会稍微滚动然后停止,并需要多次单击才能使其正常工作。我无法在不同的浏览器、桌面和移动设备上重现这个问题(当然),但我想我会尝试这种简单的方法。动画/平滑组件很好,但如果这种方法可以解决它,我也可以不用它。 - clamum

15

我自己设法做到了。不需要任何插件。请查看我的gist

// Replace #fromA with your button/control and #toB with the target to which     
// You wanna scroll to. 
//
$("#fromA").click(function() {
    $("html, body").animate({ scrollTop: $("#toB").offset().top }, 1500);
});

你的一行代码片段带有动画效果,正是我所需要的。谢谢! - Scott Smith
“不需要任何插件”?但是你使用了jQuery!它是一个非常庞大的库,甚至不是一个插件。 - Green
2
我是说,除了jQuery库引用之外,您不需要添加其他引用。此外,jQuery算是行业标准。为什么不使用它呢?也许没有jQuery也可以做到,但仍需要有人编写大量代码来进行解析。这感觉很低效。而且,仅仅为了滚动到一个简单的div,编写一个完整的插件也感觉很低效。 - lorddarq

6
您可以在JavaScript中使用scrollIntoView()方法。只需给定ID,就可以使用id.scrollIntoView();
例如:
row_5.scrollIntoView();

如何进行动画处理? - Green
当您使用scrollIntoView()时,控件将自动滚动以使其显示在视图中。 - Tamilarasi

4

1
链接已经失效了,请您更新一下吗? - Lucky

3

将元素滚动到容器中心

将元素置于容器中心。

在CODEPEN上查看演示

JS

function scrollToCenter() {
  var container = $('.container'),
    scrollTo = $('.5');

  container.animate({
    //scrolls to center
    scrollTop: scrollTo.offset().top - container.offset().top + scrollTo.scrollTop() - container.height() / 2
  });
}

HTML

<div class="container">
   <div class="1">
    1
  </div>
  <div class="2">
    2
  </div>
  <div class="3">
    3
  </div>
  <div class="4">
    4
  </div>
  <div class="5">
    5
  </div>
  <div class="6">
    6
  </div>
  <div class="7">
    7
  </div>
  <div class="8">
    8
  </div>
  <div class="9">
    9
  </div>
  <div class="10">
    10
  </div>


</div>
<br>
<br>
<button id="scroll" onclick="scrollToCenter()">
  Scroll
</button>

css

.container {
  height: 60px;
  overflow-y: scroll;
  width 60px;
  background-color: white;
}

它不是完全准确到中心位置,但在更大的元素上您不会注意到它。


2
你可以通过jQueryJavaScript来实现滚动功能,只需要使用这两个元素和以下JavaScript代码:
$(function() {
  // Generic selector to be used anywhere
  $(".js-scroll-to-id").click(function(e) {

    // Get the href dynamically
    var destination = $(this).attr('href');

    // Prevent href=“#” link from changing the URL hash (optional)
    e.preventDefault();

    // Animate scroll to destination
    $('html, body').animate({
      scrollTop: $(destination).offset().top
    }, 1500);
  });
});

$(function() {
  // Generic selector to be used anywhere
  $(".js-scroll-to-id").click(function(e) {

    // Get the href dynamically
    var destination = $(this).attr('href');

    // Prevent href=“#” link from changing the URL hash (optional)
    e.preventDefault();

    // Animate scroll to destination
    $('html, body').animate({
      scrollTop: $(destination).offset().top
    }, 1500);
  });
});
#pane1 {
  background: #000;
  width: 400px;
  height: 400px;
}

#pane2 {
  background: #ff0000;
  width: 400px;
  height: 400px;
}

#pane3 {
  background: #ccc;
  width: 400px;
  height: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav">
  <li>
    <a href="#pane1" class=" js-scroll-to-id">Item 1</a>
  </li>
  <li>
    <a href="#pane2" class="js-scroll-to-id">Item 2</a>
  </li>
  <li>
    <a href="#pane3" class=" js-scroll-to-id">Item 3</a>
  </li>
</ul>
<div id="pane1"></div>
<div id="pane2"></div>
<div id="pane3"></div>
<!-- example of a fixed nav menu -->
<ul class="nav">
  <li>
    <a href="#pane3" class="js-scroll-to-id">Item 1</a>
  </li>
  <li>
    <a href="#pane2" class="js-scroll-to-id">Item 2</a>
  </li>
  <li>
    <a href="#pane1" class="js-scroll-to-id">Item 3</a>
  </li>
</ul>


2
不确定为什么没有人说出显而易见的事实,因为有一个内置的JavaScript scrollTo函数:
scrollTo( $('#element').position().top );

参考文献


6
scrollTo需要两个参数,你只写了一个。 - NuclearPeon
2
...并且它被称为窗口对象上的。 - hashchange

1

我结合了其他人发布的内容,做到了简单和流畅。

 $('#myButton').click(function(){
        $('html, body').animate({
            scrollTop: $('#scroll-to-this-element').position().top },
            1000
        );
    });

@AnriëtteMyburgh 我不确定position()函数在所有浏览器中是否可用。你尝试过在其他浏览器中使用它来查看它是否有效吗?或者我可以看一下你正在使用的代码,看看是否有其他问题? - Nlinscott

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接