具有固定标题和固定列的可滚动HTML表

时间:2011-12-23 20:09:41

标签: html html-table scroll

我想创建一个包含可滚动数据的表。我必须冻结表格的第一行和第一列。表格的第一行和第一列必须在宽度和高度上自动调整为表格内容区域中的可变单元格尺寸(因为用户将添加具有可变内容量的新表格单元格)。

有人问了一个相关的问题: How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

但是在线演示和源代码的链接已经死了,所以我无法确认解决方案。

3 个答案:

答案 0 :(得分:4)

使用优秀的jQuery DatablesFixedHeader扩展名。

向下滚动标题行,您会看到它整齐地粘在屏幕顶部。

对于页眉,页脚,左右兴奋:

http://datatables.net/release-datatables/extras/FixedHeader/top_bottom_left_right.html

答案 1 :(得分:3)

好的,我在网上看了很多答案,最后组装了一个有效的演示版。我正在使用PHP在表中创建50行,但您可以轻松地对数据进行硬编码。我基本上创建了四个象限(div.q1,div.q2,div.q3和div.q4),其中第四象限包含实际数据表。我使用jquery将第四象限中的表复制到第二和第三象限,然后同步它们的滚动条。我使用CSS溢出,宽度,高度和显示属性的组合来隐藏每个象限中不必要的TD元素。这是一个完整的工作示例:

<html>
<head>
<style>
body {width:350px;}
.q1, .q2, .q3, .q4 {overflow:hidden; display:block; float:left;}
.q1 {width:50px; height: 30px;}
.q2 {width:300px; height: 30px;}
.q3 {width:50px; height: 100px;}
.q4 {width:300px; height: 100px; overflow:auto;}

.q2 .firstCol, .q3 thead, .q4 thead, .q4 .firstCol {display:none;}
.q2 td {background-color:#999;}
.q3 td {background-color:#999;}
.container {width:9999px;}

</style>

<script src="http://code.jquery.com/jquery-1.7.min.js"></script>
<script>
$(document).ready(function(){
   $('.q4').bind('scroll', fnscroll);
   $('.q2').html($('.q4').html());
   $('.q3').html($('.q4').html());
});

function fnscroll(){

$('.q2').scrollLeft($('.q4').scrollLeft());
$('.q3').scrollTop($('.q4').scrollTop());


}

</script>
</head>


<body>
         <div class="q1"><div class="container"></div></div>
         <div class="q2"><div class="container"></div></div>
         <div class="q3"><div class="container"></div></div>
         <div class="q4">
            <div class="container">
            <table>
               <thead>
                  <tr>
                     <td class="firstCol"></td>
                     <td>Col</td>
                     <td>Col</td>
                     <td>Col</td>
                     <td>Col</td>
                     <td>Col</td>
                     <td>Col</td>
                     <td>Col</td>
                     <td>Col</td>
                  </tr>
               </thead>
               <tbody>
               <?php for($c=0; $c<50; $c++) { ?>
                  <tr>
                     <td class="firstCol">Row</td>
                     <td>this is some content</td>
                     <td>hello world!<br/>This is good</td>
                     <td>Row</td>
                     <td>adjfljaf oj eoaifj </td>
                     <td>ajsdlfja oije</td>
                     <td>alsdfjaoj f</td>
                     <td>jadfioj</td>
                     <td>jalsdjf oai</td>
                  </tr>
               <?php } ?>
               </tbody>
            </table>
            </div>
         </div>
</body>
</html>

答案 2 :(得分:1)

您将表格渲染两次:

  • 一旦包含在所需大小的可滚动div中
  • 进入一个小div,不可滚动的div(溢出:隐藏),位于另一个顶部的顶部,隐藏它的顶行而不是滚动条
相关问题