【问题标题】:Get id of top viewable table row when Div Scroll event fires当 Div Scroll 事件触发时获取顶部可视表行的 id
【发布时间】:2014-10-09 19:22:20
【问题描述】:

我在一个可滚动的 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.
});

【问题讨论】:

    标签: jquery ajax asp.net-mvc-3


    【解决方案1】:

    如果引用不存在的封闭&lt;div&gt; 的最近祖先,则您发布的代码根本不起作用,因为$(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());
    });
    

    【讨论】:

    • 感谢您的回复。我现在正在研究这个。
    • 谢谢 :) 它对我的需求有所帮助。如果有人需要不可见行的数据,他们可以选择行索引而不是可见索引。
    猜你喜欢
    • 1970-01-01
    • 2022-08-12
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 2015-09-21
    • 2014-04-03
    • 2011-12-24
    • 1970-01-01
    相关资源
    最近更新 更多