DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
探究 DIV 的顯示與隱藏:style.display 與四大內容屬性
編輯:CSS詳解     

對 DIV 的操作是前端互動的基礎,其中顯示與隱藏的切換最為常用。本文整理相關語法與容易混淆的內容屬性。

一、控制 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 等顯示類型。

二、innerHTML、outerHTML、innerText、outerText

這四個屬性經常混淆。以下用一段範例來區分:

<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);">

實際按下各按鈕後,可以清楚看出差異:

  • innerHTML:取得 div 內部的 HTML 標籤內容(不含 div 本身)。透過它可以方便地設定 div 裡要顯示的內容,例如:
    document.getElementById("div3").innerHTML = "<strong>hhh</strong>";
  • outerHTML:包含 div 標籤本身在內的所有 HTML。
  • innerText:取得 div 內顯示的純文字,會去除標籤。
  • outerText:效果與 innerText 基本相同。

三、跨瀏覽器相容性的重要提醒

這四個屬性中,只有 innerHTML 在 Firefox 下有效,其餘三個僅在 IE 中可用。這是舊時代遺留下來的差異。

實務建議:

  1. 設定 HTML 內容時,一律使用 innerHTML。它同時支援讀取與寫入,且跨瀏覽器一致。
  2. 需要純文字時,用 textContent 取代 innerText。它支援度更廣,且不會觸發 reflow 造成的效能問題。
  3. 避免 innerHTML 拼接使用者輸入。這會造成 XSS 風險。若內容來自表單或外部資料,改用 textContent 或建構 DOM 節點的方式插入。

最後一點尤其重要:innerHTML 方便,但它會把字串當成 HTML 解析。任何未經驗證的外部內容直接塞進去,都等於在頁面上開了一扇門。

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