我正在使用 contenteditable div,当我尝试粘贴带有样式的内容时,假设只复制纯文本,但它也获得了样式,有谁知道在我粘贴时如何强制将其转换为纯文本或者任何人有更好的解决方案
这是我的代码:
<div contenteditable="true">
This text can be edited by the user.
</div>
Run Code Online (Sandbox Code Playgroud)
epa*_*llo 19
当您粘贴富内容时,它将显示为富内容。因此,您需要捕获粘贴事件,阻止默认操作,并从剪贴板读取文本。
var ce = document.querySelector('[contenteditable]')
ce.addEventListener('paste', function (e) {
e.preventDefault()
var text = e.clipboardData.getData('text/plain')
document.execCommand('insertText', false, text)
})Run Code Online (Sandbox Code Playgroud)
[contenteditable] {
background-color: black;
color: white;
width: 400px;
height: 200px;
}Run Code Online (Sandbox Code Playgroud)
<div contenteditable="true"></div>
<div>
<h1>Test content</h1>
<p style="color:red">Copy <em>this</em> <u>underlined</u></p>
</div>Run Code Online (Sandbox Code Playgroud)
小智 8
您可以将contenteditable属性值设置为plaintext-only这样:
<div contentEditable="plaintext-only"></div>
Run Code Online (Sandbox Code Playgroud)
表示元素的原始文本是可编辑的,但富文本格式被禁用
基于 WebKit 的浏览器支持一个非标准user-modifyCSS 属性:
-webkit-user-modify: read-write-plaintext-only;
Run Code Online (Sandbox Code Playgroud)
这样就无需使用已弃用的execCommandAPI 或容易出错的步骤来正确定位插入符。
-webkit-user-modify: read-write-plaintext-only;
Run Code Online (Sandbox Code Playgroud)
[contenteditable] {
-webkit-user-modify: read-write-plaintext-only;
}Run Code Online (Sandbox Code Playgroud)
有一种奇怪的行为:通过双击选择的复制粘贴文本可能会引入额外的前导和/或尾随空格(至少在 macOS 上)。
要支持非WebKit浏览器,仍然需要监听paste事件,例如:
someEditableElement.addEventListener("paste", function (e) {
e.preventDefault();
const text = e.clipboardData ? e.clipboardData.getData("text/plain") : "";
if (document.queryCommandSupported?.("insertText")) {
return document.execCommand("insertText", false, text);
}
const selection = document.getSelection();
if (!selection) return;
const range = selection.getRangeAt(0);
range.deleteContents();
range.insertNode(new Text(text));
range.collapse(); // select nothing
selection.removeAllRanges(); // position caret after inserted text
selection.addRange(range); // show caret
});
Run Code Online (Sandbox Code Playgroud)
这两种方法之间存在差异。请自行斟酌。