直入正題,現在有這麼一個表格:

要求:鼠標移到交易內容區域時,高亮當前行的背景。
談到標準的 HTML 結構,有人可能會說,用 div 標籤裡再套一層 li,最後用 CSS float 一擺,不就排成這樣了嗎?其實真正標準的結構並不是非用 div 布局不可,而是要盡量使用語義化的 HTML 標籤。在 HTML 標籤的定義中,div 與 span 其實是兩個沒有語義的標籤,而 table 則帶有「數據表」的語義。所以這裡我們來建一張符合 XHTML 1.0 Strict 的表格結構:
<table>
<thead>
<tr><th>交易類型</th><th>交易號</th><th>收款方</th><th>金額</th><th>管理</th></tr>
</thead>
<tfoot>
<tr><td colspan="5">上一頁 2 3 4 下一頁</td></tr>
</tfoot>
<tbody>
<tr><td>即時到賬</td><td>20081009001</td><td>...</td><td>...</td><td>...</td></tr>
</tbody>
</table>
需要注意的是:
再給它們加上樣式:
.tableList {
border:2px #666 solid;
}
.tableList td, .tableList th {
border:1px #666 solid;
padding:5px 25px;
}
.tableList tfoot td {
text-align:right;
}
.fastpayIcon {
background:transparent url(https://img.alipay.com/pimg/icon_fastpay16.gif) no-repeat scroll 5px 5px;
}
要實現鼠標滑過高亮,用 JS 綁定 onmouseover 和 onmouseout 當然可以。但若想符合 Web 標準,更應該用 CSS 的 hover 偽類。在 <style> 部分再加上這條規則:
.tableList tbody tr {
background:#fff;
}
.tableList tbody tr:hover {
background:#eee;
}
這樣大部分標準瀏覽器都能實現效果了。接下來考慮兼容性,為 IE6 補一段 JS:
<!--[if lt IE 7]><script type="text/javascript">
function fnHighlightTr(tableId,color,hColor){
var aTr = document.getElementById(tableId).getElementsByTagName("tbody")[0].getElementsByTagName("tr");
var nTrLen = aTr.length;
for(var i=0;i<nTrLen;i++){
aTr[i].onmouseover = function(){ this.style.backgroundColor = hColor; }
aTr[i].onmouseout = function(){ this.style.backgroundColor = color; }
}
}
fnHighlightTr("table1","#fff","#eee");
</script><![endif]-->
這裡要注意:用 IE 條件注釋 <!--[if lt IE 7]> 確保這段 JS 只在 IE7 以下版本運行,因為對其他瀏覽器而言,它是多此一舉的。
接下來在各種瀏覽器中測試兼容性,各版本 IE 建議用 IETester,再加上 FF2/FF3。測試發現,在 IE6 和 IE7 中,第一個帶背景圖片的單元格無法實現高亮,而 IE8 和 FF 沒有此問題。原因出在:
.fastpayIcon {
background:transparent url(https://img.alipay.com/pimg/icon_fastpay16.gif) no-repeat scroll 5px 5px;
}
它等價於:
.fastpayIcon{
background-attachment: scroll;
background-color: transparent;
background-image: url(https://img.alipay.com/pimg/icon_fastpay16.gif);
background-repeat: no-repeat;
background-position: 5px 5px;
}
其中定義了 background-color: transparent;,理論上是透明,但調試中發現 IE 對 td 的 background-color 支持有 BUG:設為 transparent 時,實際呈現的是 #fff。解決辦法就是刪掉對 td 的 background-color 定義,或把屬性值設為 inherit,這樣 td 就會從父元素 tr 繼承背景色,從而正確實現高亮效果。