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

Joh*_*ohn 5 html scroll html-table

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

有人问了一个相关的问题: 如何在滚动时锁定表格的第一行和第一列,可能使用JavaScript和CSS?

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

Joh*_*ohn 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>
Run Code Online (Sandbox Code Playgroud)