首页 > 解决方案 > CSS - 多行的粘性定位

问题描述

我试图在滚动表格时锁定一定数量的行以“固定”。问题:
1)要锁定的行数不同(并非总是只有列标题),因此不能依赖固定数量。
2)每行的高度可能会因内容而异,因此它不是相等的高度,也不是任何已知值。
3)由于表格和内容是动态创建的,并且可以在运行时修改,因此响应式解决方案将是最好的。

给定以下CSS(假设tad中的所有行都被“锁定”):

thead th{ position:sticky; }

然后是 JavaScript 方法(tbl 是表格元素):

var i,j,h=0,r; // Set the "top" of next "locked" rows
for(i=0 ; i<tbl.thead.rows.length ; i++) {
    r=tbl.thead.rows[i];
    for(j=0 ; j<r.cells.length ; j++)
        r.cells[j].style.top=h+"px";
    h+=r.offsetHeight;
}

主要问题:我更喜欢使用 CSS(如果可能的话)。我提出的最佳“解决方案”只能删除内部循环,但使用动态控制的 <style> 元素(假设 stl 是 STYLE 元素的句柄):

var rules="",i,h=0; // Set the "top" of next "locked" rows
for(i=0 ; i<tbl.thead.rows.length ; i++) {
    rules+="thead tr:nth-child("+(i+1)+") th{ top:"+h+"px; }\n";
    h+=tbl.thead.rows[i].offsetHeight;
}
/*
I know is possible to use stl.sheet.insertRule(),
but as I overwrite ALL rules whenever there is change, I have chosen this way.
*/
stl.innerHTML=rules;

但是,这需要与标题行一样多的规则。

问题:制定一个可以产生相同效果的规则的任何解决方案?是否可以使用纯 CSS(响应式解决方案)来实现?

注意:表格可以在页面上的任何位置,但在具有溢出:自动的容器内。

非常感谢

标签: javascriptcss

解决方案


有一个非常简单的解决方案,使广告具有粘性,而不是单独的行

.container {
    height: 250px;
    width: 200px;
    overflow: auto;
}

th {
    height: 60px;
}


#second {
    height: 80px;
    background-color: lightblue;
}

thead {
    position: sticky;
    top: 0px;
}
<div class="container">
<table>
    <thead>
    <tr>
        <th>h row 1</th>
    </tr>
    <tr>
        <th id="second">h row 2</th>
    </tr>
    </thead>
    <tr>
        <td>data</td>
    </tr>
    <tr>
        <td>data</td>
    </tr>
    <tr>
        <td>data</td>
    </tr>
    <tr>
        <td>data</td>
    </tr>
    <tr>
        <td>data</td>
    </tr>
    <tr>
        <td>data</td>
    </tr>
    <tr>
        <td>data</td>
    </tr>
    <tr>
        <td>data</td>
    </tr>
    <tr>
        <td>l data</td>
    </tr>
</table>
</div>


推荐阅读