JQuery:如何计算要在容器中显示的行数

JQuery: How to calculate the number of rows to show within a container

本文关键字:显示 何计算 计算 JQuery      更新时间:2024-05-26

有点难以解释,但让我试试:
我想把一张桌子放在一个容器里。这个容器有一个固定的高度,比如500px,表相当长,比如2100,每行的高度可以不同。

当创建表时,所有的行都是不可见的,现在我想根据容器的高度进行计算,以找出容器内应该出现多少行。它可以是前15行或前17行(因为有些行的高度更大)。

在我这样做之后,我让这些行在那里停留一段时间,然后再次隐藏它们,并进行另一次计算以获取下一页,等等…现在最困难的部分是我如何使用jquery进行计算?

您可以使用jQuery.innerHeightjQuery.outerHeight函数获得浏览器计算的高度。因此,您可以首先获得容器的计算高度。然后,您可以遍历行并添加它们的计算高度,直到总和大于容器的计算高度为止,依此类推。

希望这能有所帮助。

这并没有解决"停留一段时间并在一段时间后获取下一组行"部分,但这里有一个简单的高度计算,显示了适当的行。

http://jsfiddle.net/yvAtW/

JS-

allowedHeight = $("div").height();
actualHeight = 0;
$("tr").each(function(){
    actualHeight += $(this).height();
    if(actualHeight < allowedHeight) {
        $(this).show();
    }
});
​

HTML

<div>
<table>
    <tr class="height0">
        <td>Row</td>
    </tr>
    <tr class="height1">
        <td>Row</td>
    </tr>
    <tr class="height2">
        <td>Row</td>
    </tr>
    <tr class="height1">
        <td>Row</td>
    </tr>
    <tr class="height0">
        <td>Row</td>
    </tr>
</table>
</div>​

CSS

div{
    height:100px; /* fixed height container */
    overflow:hidden; /* Ensures no overflowing content if JS doesn't work */
    padding:10px 15px;
    background:#777;
}
table{
    width:100%;
}
tr{
    display:none; /* all hidden by default */
}
/* different height trs */
.height0{
    height:20px;
    background:#900;
}
.height1{
    height:30px;
    background:#090;
}
.height2{
    height:40px;
    background:#009;
}​

遍历行的高度总和。一旦你超过500行,除了最后一行,就把这一组行拿走。显示这些。使用某种标记,可能是一个变量或一个数据注释来跟踪您所处的位置。

也许你可以这样做:

fits = true;
while(fits){
    $(table).append('<tr>...</tr>');
    if($(table).css('height') >= $('#container').css('height'))
        fits = false;
}