
有許多的鎖定或固定html表格表頭的方法和技術,本文介紹的是一個基于IE和CSS的簡易實現(xiàn)方法,基本思路為:使用div行級元素確定一個包含表格的區(qū)域,在區(qū)域滾動移動時定位非固定單元格的位置(top/left)。
定義一個有邊框的div元素,并設置其overfloaw屬性為scroll,保證該區(qū)域恒有一個垂直與水平滾動條。
在div中嵌入一個表格,設置collapse屬性為collapse,滿足單邊框(合并邊框)的外觀。
需要設計三種類型的鎖定單元格:垂直方向鎖定單元格(VLocked)、水平方向鎖定單元格(HLocked)及雙向鎖定單元格(Locked),而一般表格內(nèi)容單元格則設置其位置屬性position為relative,見如下css代碼:
td 
{
position: relative; padding: 5px; border-top: solid 0px gray; border-bottom: solid 1px gray; border-left: solid 0px gray; border-right: solid 1px gray;
}
鎖定表格行頭時,要求行頭的單元格水平方不移動,即區(qū)域移動時重定位這些行頭單元格的left邊界值,見如下css代碼:
td.HLocked /* 水平方向鎖住單元格 */
{
z-index: 10; position: relative; left: exPRession(parentNode.parentNode.parentNode.parentNode.scrollLeft); background-color: #cccccc; text-align: center; border-top: solid 0px gray; border-bottom: solid 1px gray; border-left: solid 0px gray; border-right: solid 1px gray;
}
需要指出,表格td元素的parentNode元素是tr,tr.parentNode元素是tbody,tbody.parentNode元素是table,所以td.parentNode.parentNode.parentNode.parentNode是定制的div元素,即當前表格區(qū)域。
鎖定表格列頭時,需要考慮兩種情況單元格。一種是不鎖定行頭的單元格,此時只需要垂直方向不移動即可,見如下css代碼:
td.VLocked
{
z-index: 20; position: relative; top: expression(parentNode.parentNode.parentNode.parentNode.scrollTop); font-size: 10pt; color: black; background-color: #cccccc; text-align: center; border-top: solid 0px gray; border-bottom: solid 1px gray; border-left: solid 0px gray; border-right: solid 1px gray;
}
另一種是鎖定行頭單元格時,這些是行頭又是列頭的單元格必須雙向鎖定,見如下css代碼:
td.Locked
{
z-index: 30; position: relative; top: expression(parentNode.parentNode.parentNode.parentNode.scrollTop); left: expression(parentNode.parentNode.parentNode.parentNode.scrollLeft); font-size: 10pt; color: black; background-color: #cccccc; text-align: center; border-top: solid 0px gray; border-bottom: solid 1px gray; border-left: solid 0px gray; border-right: solid 1px gray;
}
還有兩點需要說明:
下面是完整的css代碼和htm演示代碼,測試時需要建立一個IIS虛擬路徑,拷貝css文件和htm文件到該虛擬路徑中,然后通過瀏覽器瀏覽htm文件:
新聞熱點
疑難解答