【问题标题】:Freeze the first 2 rows of a table冻结表格的前 2 行
【发布时间】:2016-05-12 16:20:35
【问题描述】:

我见过 Jquery 插件和 CSS 样式来冻结表格的标题。有没有冻结前两行。我的第二行包含一个用于搜索的文本框。我不能为行指定固定宽度。

 <table>
 <thead>
  <tr>
     <th>Month</th>
     <th>Savings</th>
  </tr>
 </thead>
<tbody>
  <tr>
     <td><input type="text"/></td>
     <td><input type="text"/></td>
  </tr>
  <tr>
     <td>February</td>
     <td>$80</td>
  </tr>
 </tbody>
</table>

【问题讨论】:

  • 你会使用 DataTables 吗?
  • “冻结”是什么意思?
  • @Aziz 冻结标题。固定标题。
  • 那么,添加position: fixed; 会发生什么?您可以使用 tr:nth-child(-n+2) 伪选择器使用 CSS 定位表的第一行
  • 这些插件将任何 CSS 样式应用于标题行也需要应用于 tbody tr:first-child

标签: jquery html css


【解决方案1】:

看起来@KarlDawson 使用DataTables 的建议可行。这是一个工作演示: http://jsfiddle.net/C8Dtf/1903/

<table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
    <thead>
        <tr>
            <th>Rendering engine</th>
            <th>Browser</th>
            <th>Platform(s)</th>
            <th>Engine version</th>
            <th>CSS grade</th>
        </tr>
        <!-- 2nd header row that will also be frozen -->
        <tr>
            <th>2Rendering engine</th>
            <th>2Browser</th>
            <th>2Platform(s)</th>
            <th>2Engine version</th>
            <th>2CSS grade</th>
        </tr>
    </thead>
    <tbody>
        <tr class="gradeX">
            <td>Trident</td>
            <td>Internet
                 Explorer 4.0</td>
            <td>Win 95+</td>
            <td class="center">4</td>
            <td class="center">X</td>
        </tr>
        <tr class="gradeC">
            <td>Trident</td>
            <td>Internet
                 Explorer 5.0</td>
            <td>Win 95+</td>
            <td class="center">5</td>
            <td class="center">C</td>
        </tr>
        ...
    </tbody>
</table>

JS:

$(document).ready( function () 
{
    var iStart = new Date().getTime();
    var oTable = $('#example').dataTable( 
    {
        "sScrollY": "300px",
        "sScrollX": "100%",
        "sScrollXInner": "150%",
        "bScrollCollapse": true,
        "bPaginate": false,
        "bFilter": false
    } );
    new FixedColumns( oTable, 
    {
        "sHeightMatch": "none"
    } );
} );

改编自这个答案:https://stackoverflow.com/a/15826692/560114。我不熟悉 DataTable 插件的细节,但应该可以调整您的 HTML,使其与此演示类似。

【讨论】:

    【解决方案2】:

    我想你想要这样的东西-

    这是纯 css 不需要其他脚本..

    查看此网址:

    codepen.io/mastershine/pen/gPdaPL

    【讨论】:

    • 嗨,webmasteravi。请阅读“How do I write a good answer
    • @webmasteravi 在示例中,第二行不固定(冻结),它在滚动时向上移动。
    • @webmasteravi 没有附带代码摘录的外部链接是有问题的,因为有时链接会关闭或不可用......并且在不依赖外部链接的情况下,关于 SO 的答案至少应该是完整的。
    猜你喜欢
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    相关资源
    最近更新 更多