繁体   English   中英

CSS - 多行的粘性定位

[英]CSS - sticky positioning of more than one row

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

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

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;

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

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

注意:该表可以在页面上包含任何 position,但位于具有溢出:自动的容器内。

非常感谢

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

 .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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM