我有一个大表与垂直滚动条。 我想使用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>


当前回答

死很简单。不需要插件。

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的文档。

其他回答

我结合了其他人发布的内容。它简单流畅

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

死很简单。不需要插件。

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的文档。

我同意Kevin和其他人的观点,使用插件是没有意义的。

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

你可以使用jQuery scrollTo插件插件:

$('div').scrollTo('#row_8');

我意识到这不能解决在容器中滚动的问题,但人们发现它很有用,所以:

$('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)