contenteditable 属性 "plaintext-only" 值组合现已成为 Baseline 新增功能

发布时间:2025 年 3 月 20 日

当您希望允许用户输入纯文本信息时,您的第一反应可能是使用 <textarea>。这在许多情况下都适用,并且无需特别努力即可使其与表单一起使用,但也存在局限性。

一个例子是使 <textarea> 随着内容动态增长,而无需使用 hack。有 field-sizing: content,但它的浏览器支持有限。这就是 contenteditable="plaintext-only" 属性值组合的用武之地。您可以将其添加到通用元素(如 <div>)中,并让元素自动处理大小调整。

另一个限制是样式设置。CSS Custom Highlight API 提供了一种机制,用于通过使用 JavaScript 创建范围并使用 CSS 设置样式来设置文档上任意文本范围的样式。<textarea> 在用户代理阴影根中内部使用 <div>,这就是为什么使用 CSS Custom Highlight API 设置文本样式不起作用的原因。如果在您已设为 contenteditable<div> 等元素上使用,则 CSS Custom Highlight API 可以正常工作。

<style>
  ::highlight(highlight) {
    background-color: yellow;
    color: black;
  }
</style>

<div contenteditable="plaintext-only">Edit me</div>

<script>
  const parentNode = document.querySelector('div').firstChild;
  const range = new Range();
  range.setStart(parentNode, 0);
  range.setEnd(parentNode, 3);
  const highlight = new Highlight(range);
  CSS.highlights.set('highlight', highlight);
</script>

Chrome DevTools Elements panel inspecting a textarea showing that it's using a div in a user-agent shadow root.

以下是 演示的屏幕截图,显示了此限制。请注意 <textarea> 中的文本未设置样式,但两个 contenteditable 通用 <div> 元素中的文本已设置样式。

Demo showing how the CSS Custom Highlight API only works with the contenteditable div elements, but not the textarea.