如何使用 jQuery 滚动到特定项目? [英] How to scroll to specific item using jQuery?
本文介绍了如何使用 jQuery 滚动到特定项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有垂直滚动条的大表格.我想使用 jQuery/JavaScript 滚动到此表中的特定行.
是否有内置方法可以做到这一点?
div {宽度:100px;高度:70px;边框:1px纯蓝色;溢出:自动;}
<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>
解决方案
死的简单.无需插件.
var $container = $('div'),$scrollTo = $('#row_8');$container.scrollTop($scrollTo.offset().top - $container.offset().top + $container.scrollTop());//或者您可以为滚动设置动画:$container.animate({scrollTop: $scrollTo.offset().top - $container.offset().top + $container.scrollTop()});
这是一个工作示例.
scrollTop
的文档.
I have a big table with vertical scroll bar. I would like to scroll to a specific line in this table using jQuery/JavaScript.
Are there built-in methods to do this?
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>
解决方案
Dead simple. No plugins needed.
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()
});
Here is a working example.
这篇关于如何使用 jQuery 滚动到特定项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文