带固定标题和固定列的可滚动HTML表格
问题描述:
我想创建一个带有可滚动数据的表格。我必须冻结表格的第一行和第一列。表格的第一行和第一列必须自动调整表格内容区域中可变单元格的宽度和高度(因为用户将添加具有可变内容量的新表格单元格)。带固定标题和固定列的可滚动HTML表格
有人问一个相关的问题: How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?
但链接在线演示和源代码是死的,所以我无法确认解决方案。
答
好吧,我读了很多网络上的答案,并最终组装了一个演示,工作。我使用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>
答
您呈现表两次:
- 在你想要的大小的可滚动DIV在一个小格,非滚动股利(溢出:隐藏)一旦包含
- 一次,也就是定位在顶部隐藏它的顶部行,但不是滚动条
答
使用优秀jQuery Datables与FixedHeader扩展。
向下滚动标题行,你会看到它自己整洁地粘贴到屏幕的顶部。
对于页眉,页脚,左,右的兴奋:
http://datatables.net/release-datatables/extras/FixedHeader/top_bottom_left_right.html
这是伟大的。只是在这里添加了一个小提琴http://jsfiddle.net/9NcnH/ – dotnetcoder 2013-08-24 23:38:18
我们如何根据内容动态调整q3的宽度,而不是将其设置为50px? – dotnetcoder 2013-08-24 23:49:39