Scrollable HTML Table

我們在撰寫網頁時常常會因為資料量的關係使得網頁會超過一個檢視頁,
導致需要使用 scroll bar 將網頁網下捲才能看到全部的資料

有沒有辦法將 HTML Table 作成像 Excel 凍結視窗的方式進行資料的捲動?

上 Google 搜尋 Scrollable HTML Table
你可以找到一大串範例程式可供使用
有的直接對 DOM 操作, 有的透過 iframe 方式來模擬

介紹一個只透過 CSS 的方法, 就可以達成我們的目的了 (參考 LauDean的程式)

美美的 CSS
<style type="text/css">
DIV{
scrollbar-DarkShadow-Color:#9FB7D7;
scrollbar-Track-Color:#F7F7F7;
scrollbar-Face-Color:#C7CFFF;
scrollbar-Shadow-Color:#FFFFFF;
scrollbar-Highlight-Color:#FFFFFF;
scrollbar-3dLight-Color:#C7CFF7;
scrollbar-Arrow-Color:#4F5F87;
}
</style>

表格的部份, 首先將標題的部分獨立出來

<table border="0" cellpadding="0" cellspacing="0" style="border: solid 1px; border-collapse: collapse" width="950">
<tr>
<td valign="top">
<table border="1" cellpadding="0" cellspacing="0" style="border: solid 1px; border-collapse: collapse" width="950">
<tr class="Header">
<td nowrap="nowrap" align="center" width="40">序號<br /> </td>
<td nowrap="nowrap" align="center" width="80">客戶名稱<br /> </td>
<td nowrap="nowrap" align="center" width="50">業務員<br /> </td>
<td nowrap="nowrap" align="center" width="50">客戶<br />類別</td>
<td nowrap="nowrap" align="center" width="70">放款天數<br /></td>
<td nowrap="nowrap" align="center" width="80">A/R 合計<br />(萬元)</td>
<td nowrap="nowrap" align="center" width="90">銷售淨額<br />(萬元)</td>
<td nowrap="nowrap" align="center" width="80">銷售毛利<br />(%)</td>
<td nowrap="nowrap" align="center" width="80">信用額度<br />(萬元)</td>
<td nowrap="nowrap" align="center" width="99">信用評等</td>
<td nowrap="nowrap" align="center" width="99">EPS</td>
<td nowrap="nowrap" align="center" width="60">每股<br />淨值</td>
<td nowrap="nowrap" align="center" width="72">目前<br />股價</td>
</tr>
</table>
</td>
</tr>

再來將內容的 table 部份包裝在 Contain 的<div></div>之中, 將 <div> style 中的 overflow 功能 on 起來,

x 表示水平捲軸, y 表示垂直捲軸

scroll 表示強迫出現捲軸

auto 表示當內容超過現訂範圍時, scroll bar才會出現

<tr>
<td width="*" valign="top">
<div id="Contain" style="height:290px; overflow-y:scroll; overflow-x:auto; margin-top:-1px;">
<table id="ContentTable" border="1" cellpadding="0" cellspacing="0" style="border: solid 1px;border-collapse: collapse" width="936">
<tr>
<td align="center" width="40"> </td>
<td align="left" width="80"> </td>
<td align="center" width="50"> </td>
<td align="right" width="50"> </td>
<td align="right" width="70"> </td>
<td align="right" width="80"> </td>
<td align="right" width="90"> </td>
<td align="right" width="80"> </td>
<td align="right" width="80"> </td>
<td align="center" width="100"> </td>
<td align="right" width="100"> </td>
<td align="right" width="60"> </td>
<td align="right" width="56"> </td>
</tr>
</table>
</div>
</td>
</tr>
</table>


這樣就可以捲動 HTML 的 table 囉!!

要注意的是由於標題列與內容列是兩個獨立的表格

所以再頁面的呈現上要自行調整每一個 td 的 width 這樣才不會發生上下寬度不一致的窘境

多試幾次就可以調成美美的網頁了

這邊就示範垂直捲軸的作法, 水平捲軸的部份就留給大家自己 try 吧.

張貼留言