2011-12-23 133 views
5

我想創建一個帶有可滾動數據的表格。我必須凍結表格的第一行和第一列。表格的第一行和第一列必須自動調整表格內容區域中可變單元格的寬度和高度(因爲用戶將添加具有可變內容量的新表格單元格)。帶固定標題和固定列的可滾動HTML表格

有人問一個相關的問題: How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

但鏈接在線演示和源代碼是死的,所以我無法確認解決方案。

回答

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> 
+0

這是偉大的。只是在這裏添加了一個小提琴http://jsfiddle.net/9NcnH/ – dotnetcoder 2013-08-24 23:38:18

+0

我們如何根據內容動態調整q3的寬度,而不是將其設置爲50px? – dotnetcoder 2013-08-24 23:49:39

1

您呈現表兩次:

  • 在你想要的大小的可滾動DIV在一個小格,非滾動股利(溢出:隱藏)一旦包含
  • 一次,也就是定位在頂部隱藏它的頂部行,但不是滾動條
4

使用優秀jQuery DatablesFixedHeader擴展。

向下滾動標題行,你會看到它自己整潔地粘貼到屏幕的頂部。

對於頁眉,頁腳,左,右的興奮:

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

+0

哇!我正在尋找這些東西,但沒有意識到它是在Datatables.net網站的「額外」部分! – 321X 2013-05-23 12:37:32

+1

該鏈接已損壞,現在位於https://www.datatables.net/extensions/fixedheader/ – samson 2015-05-27 15:13:19