我在一个可滚动的div标记中有一个表。当用户向下滚动时,我想使用jQuery捕获可见TR的ID。可能会返回几百条记录。如何使用jQuery查找顶部可见的表行id?
<div id="mainDiv" style="overflow-y: scroll" class="scrollDiv">
<table id="mainTable" style="table-layout:fixed" height="900px">
<tr id="0">
<td></td>
<td></td>
</tr>
<tr id="1">
<td></td>
<td></td>
</tr>
<tr id="2">
<td></td>
<td></td>
</tr>
</table>
</div>
jQuery
$(".scrollDiv").scroll(function(){
var rowNumber = $(this).closest('tr').children('td:first').text();
//the above returns the top row visible or not. I want the first visible row.
});
如果引用的是不存在的封闭<div>
的最近祖先,则自$(this).closest('tr')...
以来,作为发布的代码根本不起作用。您需要获得div
的.scrollTop()
,并将其与div
中元素的高度进行比较。
我在这里创建了一个简单的fiddle,展示了它是如何工作的(在这种情况下,滚动容器包含div-你需要根据你的表行和你想要返回的单元格文本进行调整
html
<div id="mainDiv">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
...
</div>
<div id="message"></div>
脚本
$("#mainDiv").scroll(function () {
var rows = $(this).children('div');
var offset = $(this).scrollTop();
var visibleIndex = 0;
var height = 0;
rows.each(function (index, item) {
if (offset == 0) {
height = 0;
visibleIndex = 0
return false;
}
height += $(this).height();
if (height > offset) {
visibleIndex = index + 1;
height = 0;
return false;
}
})
$('#message').text('The text of the first fully visible div is ' + rows.eq(visibleIndex).text());
});