前言
<table> 是 HTML 結構最複雜的元素之一,手動拼接字符串極易出錯。瀏覽器提供了專門的 HTMLTableElement API,讓表格創建、修變更直觀高效。同時,CSSOM(CSS Object Model)讓 JavaScript 能夠精確控制樣式,本文將兩大主題串聯講解。
一、表格操作:告別字符串拼接,擁抱 HTMLTableElement API
1. 原生 DOM 創建表格(教學示範)
var table = document.createElement('table');
table.border = 1;
table.width = 300;
var caption = document.createElement('caption');
caption.appendChild(document.createTextNode('人員表'));
table.appendChild(caption);
var thead = document.createElement('thead');
var tr = document.createElement('tr');
['姓名', '年齡'].forEach(function(text) {
var th = document.createElement('th');
th.appendChild(document.createTextNode(text));
tr.appendChild(th);
});
thead.appendChild(tr);
table.appendChild(thead);
document.body.appendChild(table);
2. HTMLTableElement 專屬屬性與方法(推薦實戰用)
| 屬性/方法 | 說明 |
| caption | <caption> 元素引用 |
| tHead / tFoot | <thead>/<tfoot> 元素引用(唯一) |
| tBodies | <tbody> 集合(可多個) |
| rows | 所有 <tr> 集合 |
| createTHead() / createTFoot() / createCaption() | 創建並返回對應元素 |
| deleteTHead() / deleteTFoot() / deleteCaption() | 刪除對應元素 |
| insertRow(index) / deleteRow(index) | 在 rows 集合中插入/刪除行 |
3. HTMLTableSectionElement(thead/tbody/tfoot)
rows:該區塊內的行集合
insertRow(index) / deleteRow(index)
4. HTMLTableRowElement(tr)
cells:單元格集合
insertCell(index) / deleteCell(index)
5. 實戰:快速獲取表格標題
alert(table.caption.innerHTML); // 直接訪問 caption 內容
注意:<thead> 和 <tfoot> 在一個表格中只能各有一個,因此屬性返回單一元素;<tbody> 可有多個,返回集合。
二、樣式操作:從行內樣式到 CSSOM 深度控制
1. CSS 能力檢測
console.log('DOM1 CSS:', document.implementation.hasFeature('CSS', '2.0'));
console.log('DOM2 CSS:', document.implementation.hasFeature('CSS2', '2.0'));
2. 行內樣式:style 屬性
每個元素的 style 屬性返回 CSSStyleDeclaration 對象,僅反映 style 標籤內的聲明。
| CSS 屬性 | JS 屬性 |
| color | style.color |
| font-size | style.fontSize |
| float | style.cssFloat (非 IE) / style.styleFloat (IE) |
// 兼容性 float 設置
typeof box.style.cssFloat !== 'undefined'
? box.style.cssFloat = 'right'
: box.style.styleFloat = 'right';
3. cssText:批量讀寫行內樣式
box.style.cssText = 'color: red; font-size: 14px;';
console.log(box.style.cssText); // 獲取完整行內樣式字符串
4. 計算後樣式:getComputedStyle / currentStyle
獲取最終渲染樣式(含外部樣式表、繼承、瀏覽器默認值)。
var style = window.getComputedStyle
? window.getComputedStyle(box, null)
: box.currentStyle; // IE8-
console.log(style.color); // 如 rgb(255,0,0)
console.log(style.fontFamily); // 復合屬性正常
console.log(style.border); // 簡寫屬性各瀏覽器表現不一,建議用 border-top-color 等完整寫法
5. className 操作與封裝
box.className = 'red'; // 覆蓋全部 class
// 封裝工具函數
function hasClass(el, cls) {
return new RegExp('(^|\\s)' + cls + '(\\s|$)').test(el.className);
}
function addClass(el, cls) {
if (!hasClass(el, cls)) el.className += ' ' + cls;
}
function removeClass(el, cls) {
if (hasClass(el, cls)) {
el.className = el.className.replace(new RegExp('(^|\\s)' + cls + '(\\s|$)'), ' ');
}
}
6. 操作樣式表:CSSStyleSheet
通過 <link> 或 <style> 獲取 CSSStyleSheet 對象:
var link = document.getElementsByTagName('link')[0];
var styleSheet = link.sheet || link.styleSheet; // 非 IE 用 sheet,IE 用 styleSheet
// 進而可操作 cssRules / rules 集合,動態增刪改規則
總結
- 表格操作請優先使用 HTMLTableElement API,結構清晰、效能高、不易出錯。
- 樣式操作分層:
style(行內)、className(類名切換)、getComputedStyle(讀取最終值)、CSSStyleSheet(動態修改規則)。
- 寫入樣式推薦
className + CSS 類,維護性最佳;動態計算數值時用 style 屬性。
copyright ©
萬盛學電腦網 all rights reserved