特定viewpart中可见表行的数量

时间:2014-11-13 12:25:56

标签: javascript jquery html css angularjs

我在确定某个行是否在视图部分中完全可见时遇到问题。

我创建了一个虚拟表,如下所述: -

<table id="alarmTable">
    <tr>
    <td>
        Hello
    <td>
    </tr>
    <tr>
    <td>
        Hello
    <td>
    </tr>
    <tr>
    <td>
        Hello
    <td>
    </tr>
    <tr>
    <td>
        Hello
    <td>
    </tr>
    <!-- with more data in the table -->
</table>

我想确定表格行是否在视图部分中可见。假设我的表有50行,当前在浏览器窗口或其中的一小部分可见。

案例1: - 如果我将行数增加到50以上,滚动条将自动生效,但可见数仍应为50.我想要一些可以处理实际可见行的代码返回表中的行是否可见。

案例2: - 如果我重新调整浏览器窗口的大小,我的视图部分会调整大小。这次可见行的数量甚至可以小于50.我如何处理这种情况并检查行是否仍然是可见的。

到目前为止的方法: - 我尝试了很多东西,包括以下代码片段: -

var visibleRows = $('#alarmTable tr:visible').length;
console.log("visible rows =" + visibleRows);
console.log("scroll height ="+ document.getElementById("alarmTable").scrollHeight);
console.log("client height ="+ document.getElementById("alarmTable").clientHeight);
console.log("offset height ="+ document.getElementById("alarmTable").offsetHeight);

但他们没有给我正确的参数。

注意: - 上面创建的表只是一个虚拟表,可以更好地理解我的问题。 Image with all the rows visible in this case we need the row ids of the rows that are visible example in the image it is 8

In this case the rows ids of the rows that are actually visible should be returned. Half visible rows can be excluded

In this case if the window is resized the number of visible rows can be much smaller. In this case we need only the ids of the rows that are actually visible example :- in the image the number of visible rows is - 7

返回可见行的行id的代码或返回行是否可见的代码将被接受为正确答案。

1 个答案:

答案 0 :(得分:3)

以下是根据元素在视口中是否可见来过滤元素的方法

$(window).on('scroll resize', function() {

    var top    = $(this).scrollTop(),
        height = $(this).height();


    var visible = $('#alarmTable tr').filter(function() {
        var elTop    = $(this).offset().top,
            elHeight = $(this).height();

        return (elTop > top) && ((elTop + elHeight) < (top + height));
    });

});

FIDDLE

相关问题