2014-10-09 15 views
0

我在滾動的div標籤內有一個表格。當用戶向下滾動時,我想使用jQuery捕獲可見TR的ID。可能會有幾百條記錄被返回。我怎樣才能找到使用jQuery頂部可見的錶行ID?Div Scroll事件觸發時獲取頂部可視表格行的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. 
}); 

回答

3

如果指的是封閉<div>不存在的最近的祖先你的代碼張貼不會工作,因爲在所有$(this).closest('tr')...。您需要獲得div.scrollTop(),並將其與div中元素的高度進行比較。

我創建了一個simple fiddle here,顯示它如何能工作(在這種情況下,滾動容器中包含的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()); 
}); 
+0

謝謝您的答覆。我期待到現在這樣。 – codeg 2014-10-10 15:14:53

+0

謝謝:)它幫助我的需要。如果任何人需要不可見行的數據,他們可以選擇行的索引而不是可見索引。 – Sathish 2014-10-16 10:22:42