在 HTML 中检查元素内容是否可编辑

htmlweb developmentfront end technology更新于 2025/4/10 6:36:17

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"参数,使文本不可编辑。


相关文章


有用资源