檢查HTML元素內容是否可編輯


`contenteditable` 屬性指示元素的內容是否可編輯。如果內容可編輯,瀏覽器將允許透過修改其元件來進行編輯。

此屬性必須始終採用以下兩個值之一:

  • **true** 或空字串 - 表示內容可編輯

  • **false** - 表示內容不可編輯

如果屬性未採用上述任何值,則宣告為空字串,預設情況下將成為可編輯內容。

**注意** - 如果元素的 `contenteditable` 屬性未設定或無效,則其值將從其父元素繼承;這意味著如果父元素可編輯,則該元素也可編輯。

語法

HTMLElementObject.contentEditable=true|false

以下是一些例子……

示例:帶有“true”屬性值

在下面的例子中,我們使用 `contenteditable` 屬性並將值設定為“true”以使我們的文字可編輯。

<!DOCTYPE html> <html> <body> <h1>It Is Editable,Try To Change This Text.</h1> <p contenteditable="true">Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms.</p> </body> </html>

輸出

執行上述指令碼後,它將啟用文字,允許我們進行更改或使文字可編輯,因為我們將 `contenteditable` 設定為 true。

示例:帶有“false”屬性值

在下面的例子中,我們使用 `contenteditable` 屬性並將值設定為“true”以使我們的文字可編輯。

<!DOCTYPE html> <html> <body> <h1>It Is Not Editable; Try To Change This Text.</h1> <p contenteditable="false">Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms.</p> </body> </html>

輸出

執行上述指令碼後,它不會啟用文字更改或使文字可編輯,因為我們將 `contenteditable` 設定為 false。

示例:使用Javascript

在下面的例子中,我們使用 `contenteditable` 屬性值設定為“true”以使我們的文字可編輯。

<!DOCTYPE html> <html> <body> <h1>find out if text editable</h1> <p id="varma" contenteditable="true">We have established a Digital Content Marketplace to sell Video Courses and eBooks at a very nominal cost. You will have to register to avail these premium services.</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var x = document.getElementById("varma").contentEditable; } </script> </body> </html>

輸出

指令碼執行時,它會觸發 `contenteditable` 並使文字可編輯或進行更改,因為我們將 `contenteditable` 值設定為 true。

類似的 JavaScript 程式碼透過將 `contenteditable` 屬性的引數設定為“false”來使文字不可編輯。

更新於:2022年9月5日

764 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.