将contenteditable属性应用于任何HTML元素。瞧!现在,您可以像<input>或<textarea>那样工作编辑它们👍
这对于为您的用户创建无缝的流畅编辑体验很酷。他们可以简单地单击该元素,并立即对文本进行更新。如果您是使用标准<textarea>或来完成的<input>,那么您还有其他步骤,使用一些JS在不同类型的元素之间切换,或者使用某种CSS样式使它看起来不像文本,如果您知道我的意思,大声笑😂
<p contenteditable="true">...</p>
#contenteditable 属性值
可以有3个不同的值:
<p contenteditable="true">
Element is editable
</p>
<p contenteditable="false">
Element is NOT editable
</p>
<p contenteditable="inherit">
Element inherits its parent's editable status
</p>
#contenteditable 大事记
要从contendeditable元素中检索文本,您将需要附加一个事件侦听器。input每次contenteditable更改的内容都会触发该事件。
<p contenteditable="true">
Hello
</p>
var content = document.querySelector('[contenteditable]');
// 1. Listen for changes of the contenteditable element
content.addEventListener('input', function(event) {
// 2. Retrive the text from inside the element
console.log(content.innerHTML);
});
#富文本编辑 contenteditable
一个很好的用例是使用该属性将您的只读HTML元素转换为富文本编辑器。这使您的用户可以阅读内容并根据需要进行编辑。相当整齐👍