html - 滚动时修复表格标题

标签 html css reactjs html-table

我正在使用 React,尝试创建一个表,表头在主体滚动时固定在屏幕上。

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

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

此解决方案满足第 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;
}

最佳答案

试试这个代码

使用translate 固定 header

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

关于html - 滚动时修复表格标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45474445/

相关文章:

html - IE9 字体不渲染

html - 拉伸(stretch) block 元素以填充其父元素的 100% 垂直滚动高度

javascript - 如何启动 react.js 的 nuka 轮播组件?

javascript - 如何在 ReactJS 中创建动态表?

html - GitHub 标记颜色更改 HTML/CSS

html - CSS 渐变 + 噪声作为 div 背景填充

html - 我怎样才能使突出显示的下拉菜单具有透明背景

Javascript 模态 - 禁用正文滚动但使用 css 启用模态

javascript - Internet Explorer 不支持 jquery

javascript - 如何更改查询值(其中 : { }) with Apollo GraphQL