欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

使用 position:sticky 来实现表格中的固定列/固定标题 - sticky = relative + fixed,当 sticky 元素未离开视口时,它的行为是相对的(跟随文档的流程);当它离开视口时,它的行为是固定的(固定到视口中的某个位置)。

最编程 2024-03-26 19:46:15
...
table{
    border-collapse: separate;
    border-spacing: 0;
    table-layout: fixed;
}
table th,td{
    background: #ddd;
    text-align:center;
    border-right: 1px solid #000;
}
table th:first-child,td:first-child{
    border-left: 1px solid #000;
}
.table_header table th{
    border-top: 1px solid #000;
    border-bottom: 1px solid #000;
}
.table_body table tr:not(:first-child) td{
    border-top: 1px solid #000;
}
.td_fixed{
    position: sticky;
    left: 0px;
    z-index: 1;
    border-right: 1px solid #000;
}

最终效果:

image.png

补充

当然,这个效果还比较简陋,后面还可以优化的点:

  1. 给table header和 table body固定列的右侧加上阴影,在scrollTop/scrollLeft > 0 的时候显示出来
  2. 如果要将滚动条改为仅在表体中显示,则可以隐藏整个页面的滚动条,把滚动条显示在表体的table中,并且监听表体table的横向滚动,滚动时,同时调整table header的scrollLeft即可

参考

  • developer.mozilla.org/zh-CN/docs/…
  • caniuse.com/?search=sti…
  • juejin.cn/post/684490…