【问题标题】:Fix table header while scrolling滚动时修复表格标题
【发布时间】:2018-01-10 11:34:37
【问题描述】:

我正在使用 React,试图在正文滚动时创建一个标题固定在屏幕上的表格。

我检查了many solutions,但它们不满足我的以下要求:

  1. 表格必须保持打印友好(表格中的所有行都必须是可打印的)
  2. 列宽不能固定(应根据col内容的宽度)

此解决方案满足第 2 点但不满足第 1 点:https://jsfiddle.net/flytrap/g2cxd0jj/

/* this is for the main container of the table, also sets the height of the fixed header row */
.headercontainer {
  position: relative;
  border: 1px solid #222;
  padding-top: 37px;
  background: #000;
}
/* this is for the data area that is scrollable */
.tablecontainer {
  overflow-y: auto;
  height: 200px;
  background: #fff;
}

/* remove default cell borders and ensures table width 100% of its container*/
.tablecontainer table {
  border-spacing: 0;
}

/* add a thin border to the left of cells, but not the first */
.tablecontainer td + td {
  border-left:1px solid #eee; 
}

/* cell padding and bottom border */
.tablecontainer td, th {
  border-bottom:1px solid #eee;
  padding: 10px;
}

/* make the default header height 0 and make text invisible */
.tablecontainer th {
    height: 0px;
    padding-top: 0;
    padding-bottom: 0;
    line-height: 0;
    visibility: hidden;
    white-space: nowrap;
}

/* reposition the divs in the header cells and place in the blank area of the headercontainer */
.tablecontainer th div{
  visibility: visible;
  position: absolute;
  background: #000;
  color: #fff;
  padding: 9px 10px;
  top: 0;
  margin-left: -10px;
  line-height: normal;
   border-left: 1px solid #222;
}
/* prevent the left border from above appearing in first div header */
th:first-child div{
  border: none;
}

/* alternate colors for rows */
.tablecontainer tbody  tr:nth-child(even){
     background-color: #ddd;
}

【问题讨论】:

  • 请添加您当前的相关代码。
  • @I haz kode 添加了当前代码并链接到 jsfiddle
  • @Avery235 为什么不使用 JQuery Datatables 之类的插件?

标签: html css reactjs html-table


【解决方案1】:

试试这个代码

使用translate 固定标题

document.getElementById("table-container").addEventListener("scroll", function() {
  var translate = "translate(0," + this.scrollTop + "px)";
  this.querySelector("thead").style.transform = translate;

});

打印 表格中的所有行都在css中添加这个

   @media print {
       #table-container{
         height:100%;
       }
   }

DEMO

更新


使用下面更新css以避免滚动后混乱的打印

@media print {
       #table-container{
         height:100%;
       }
       #table-container thead{
         transform: none!important;
       }
   }

DEMO

【讨论】:

  • 这个解决方案需要我在我的 React 项目中包含 JQuery 吗?
  • React 强烈反对。更喜欢纯 CSS/HTML/React 解决方案。
  • 滚动表格会打乱打印。在打印之前将其重置为顶部的任何技巧?
  • 非常感谢到目前为止的帮助!最后一个问题:i.imgur.com/AdaBTa1.png 我一开始滚动,th 边框就消失了,当我滚动回顶部时,只显示部分边框:i.imgur.com/ez71b6l.png。一直试图在没有运气的情况下隔离问题一个小时。我的 CSS 与您的非常相似,并且该项目是专有的,因此我无法显示源代码。任何线索可能是什么问题?
  • 这是个好主意!我不敢相信我没有立即想到这一点。将在 React 中实现这一点。谢谢!
猜你喜欢
  • 2011-09-25
  • 1970-01-01
  • 2013-08-02
  • 1970-01-01
  • 2021-05-04
  • 2012-01-04
  • 2017-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多