HTML contenteditable 全域性屬性

Baseline 廣泛可用 *

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

* 此特性的某些部分可能存在不同級別的支援。

contenteditable 全域性屬性是一個列舉屬性,用於指示元素是否應由使用者編輯。如果可以編輯,瀏覽器將修改其小部件以允許編輯。

試一試

<blockquote contenteditable="true">
  <p>Edit this content to add your own quote</p>
</blockquote>

<cite contenteditable="true">-- Write your own name here</cite>
blockquote {
  background: #eeeeee;
  border-radius: 5px;
  margin: 16px 0;
}

blockquote p {
  padding: 15px;
}

cite {
  margin: 16px 32px;
  font-weight: bold;
}

blockquote p::before {
  content: "\201C";
}

blockquote p::after {
  content: "\201D";
}

[contenteditable="true"] {
  caret-color: red;
}

該屬性必須取以下值之一:

  • true空字串,表示元素是可編輯的。
  • false,表示元素不可編輯。
  • plaintext-only,表示元素的純文字可編輯,但富文字格式被停用。

如果屬性未賦值,例如 <label contenteditable>Example Label</label>,則其值被視為空字串。

如果此屬性缺失或其值無效,則其值將從其父元素繼承:因此,如果父元素可編輯,則該元素也可編輯。

請注意,儘管其允許的值包括 truefalse,但此屬性是一個列舉屬性,而不是布林屬性。

您可以使用 CSS caret-color 屬性來設定用於繪製文字插入插入符的顏色。

透過使用 contenteditable 屬性而變得可編輯(因此具有互動性)的元素可以獲得焦點。它們參與順序鍵盤導航。但是,巢狀在其他 contenteditable 元素中的帶有 contenteditable 屬性的元素預設不會新增到製表符序列中。您可以透過指定 tabindex 值(tabindex="0")將巢狀的 contenteditable 元素新增到鍵盤導航序列中。

如果內容被貼上到 contenteditable="true" 的元素中,則所有格式都會保留。如果內容被貼上到 contenteditable="plaintext-only" 的元素中,則所有格式都會被移除。

示例

將內容貼上到 contenteditable 中

此示例有兩個帶有 contenteditable<div> 元素,第一個值為 true,第二個值為 plaintext-only。複製下面的內容並貼上到每個 div 中,以檢視其效果。

HTML

html
<h2>Pasting areas</h2>
<section class="pasting">
  <div class="wrapper">
    <h3>contenteditable="true"</h3>
    <div contenteditable="true"></div>
  </div>
  <div class="wrapper">
    <h3>contenteditable="plaintext-only"</h3>
    <div contenteditable="plaintext-only"></div>
  </div>
</section>

規範

規範
HTML
# attr-contenteditable

瀏覽器相容性

另見