滚动

时间:2017-08-03 03:49:04

标签: html css reactjs html-table

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

我已查看many solutions,但它们不符合我的要求:

  1. 该表必须保持打印友好状态(表中的所有行必须是可打印的)
  2. 列宽不得固定(应基于col内容的宽度)
  3. 此解决方案满足第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;
    }
    

1 个答案:

答案 0 :(得分:3)

试用此代码

使用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