DIV CSS 佈局教程網

用 JS 切換表格框線:只顯示橫線或只顯示直線
編輯:關於JavaScript     

表格預設會把每一格的四周都畫上框線,看起來像一張方格紙。多數設計稿其實只想要其中一個方向的分隔線,這時 rules 屬性就能派上用場。

 <!DOCTYPE html>
<html>
<head>
<script>
function rowRules() {
  document.getElementById('myTable').rules = "rows";
}
function colRules() {
  document.getElementById('myTable').rules = "cols";
}
</script>
</head>
<body>
<table id="myTable" border="1">
  <tr><td>Row1 cell1</td><td>Row1 cell2</td></tr>
  <tr><td>Row2 cell1</td><td>Row2 cell2</td></tr>
  <tr><td>Row3 cell1</td><td>Row3 cell2</td></tr>
</table>
<br>
<input type="button" onclick="rowRules()" value="Show only row borders" />
<input type="button" onclick="colRules()" value="Show only col borders" />
</body>
</html>

rules 的四個值

· none 不顯示任何格線
· groups 只顯示 thead/tbody/tfoot 之間的分界
· rows 只顯示列與列之間的橫線
· cols 只顯示欄與欄之間的直線
· all 全部顯示(預設)

要注意 rules 必須搭配 border 屬性才有作用。border 為 0 時,rules 無論設什麼都不會有線條。

rules 已被 HTML5 棄用

rules 屬於HOULD-frame 時代的表格屬性,在 HTML5 中已被標記為不建議使用,瀏覽器支援也不完整。現代做法是用 CSS:

 // 只顯示橫線
 document.getElementById('myTable').style.borderCollapse = "collapse";
 document.getElementById('myTable').style.borderBottom = "1px solid #ccc";

更推薦用 class 切換:

 /* CSS:只顯示橫線 */
table.rows-only { border-collapse: collapse; }
table.rows-only td { border: none; border-bottom: 1px solid #ddd; }

/* CSS:只顯示直線 */
table.cols-only { border-collapse: collapse; }
table.cols-only td { border: none; border-right: 1px solid #ddd; }
table.cols-only td:last-child { border-right: none; }  /* 最右側不要線 */

/* JS */
var t = document.getElementById('myTable');
t.classList.add('rows-only');

這裡的 border-collapse: collapse 很關鍵。相鄰儲存格的邊框在預設的 separate 模式下會各自獨立繪製,造成線條看起來有兩倍粗;collapse 會把相鄰框線合併成一條。

td:last-child 那行則是為了避免表格最外側多出一條或多一條邊線,這是實作「只顯示內部格線」時最常見的收尾修飾。

結論:rules 可以作為理解表格框線概念的入門,實際專案請一律改用 CSS,無論是維護性還是跨瀏覽器一致性都更好。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved