對 DIV 的操作是前端互動的基礎,其中顯示與隱藏的切換最為常用。本文整理相關語法與容易混淆的內容屬性。
1. 設定顯示或隱藏
document.getElementById("div1").style.display = "none"; // 隱藏
document.getElementById("div2").style.display = ""; // 顯示
也可以直接用元素名稱呼叫(需搭配 id 全域變數):
div1.style.display = "none"; // 隱藏 div2.style.display = ""; // 顯示
把 display 設為空字串,等於移除行內樣式、回到樣式表定義的值,這比設成 "block" 更安全,因為不會破壞元素原本可能具有的 inline 或 flex 等顯示類型。
這四個屬性經常混淆。以下用一段範例來區分:
<div id="div">
<input name="button" value="Button" type="button">
<font color="green">
<h2>This is a DIV!</h2>
</font>
</div>
<input name="innerHtml" value="innerHtml" type="button"
onclick="alert(div.innerHTML);">
<input name="outerHtml" value="outerHtml" type="button"
onclick="alert(div.outerHTML);">
<input name="innerText" value="innerText" type="button"
onclick="alert(div.innerText);">
<input name="outerText" value="outerText" type="button"
onclick="alert(div.outerText);">
實際按下各按鈕後,可以清楚看出差異:
document.getElementById("div3").innerHTML = "<strong>hhh</strong>";這四個屬性中,只有 innerHTML 在 Firefox 下有效,其餘三個僅在 IE 中可用。這是舊時代遺留下來的差異。
實務建議:
textContent 取代 innerText。它支援度更廣,且不會觸發 reflow 造成的效能問題。textContent 或建構 DOM 節點的方式插入。最後一點尤其重要:innerHTML 方便,但它會把字串當成 HTML 解析。任何未經驗證的外部內容直接塞進去,都等於在頁面上開了一扇門。