标准中没有规定如何将呈现的DOM中的 Select 内容转换为纯文本,因此这完全取决于您从哪个应用程序复制和/或粘贴到哪个应用程序.
有3.2.7 The innerText and outerText properties个是这样写的:
- 如果 node 是
p
元素,则在项的开始和结尾处追加2(必需的换行数).
但这仅在使用.innerText
或.outerText
时才相关;然而,如果呈现的DOM中的 Select 被转换为纯文本,则不会考虑这一点,因为那里的CSS可能会影响间距,或者如果根本没有新行.
剪贴板可以保存您复制的数据的多种表示形式.
在"粘贴"时,应用程序将在剪贴板上判断目标的最佳匹配表示(或根据用户 Select 插入的所需行为),并在必要时转换数据(使用自己的规则)
在JavaScript中,您可以在复制时覆盖剪贴板中存储的内容:
function copyListener(event) {
event.clipboardData.setData("text/html", "here we have <strong>html</strong>");
event.clipboardData.setData("text/plain", 'this is just plain text');
event.preventDefault();
};
document.addEventListener("copy", copyListener, false);
.editor {
width: 30em;
height: 10em;
border: 1px solid rgb(200, 200, 200)
}
<p>copy me</p>
<p>
Paste as Plain:
</p>
<textarea class="editor"></textarea>
<p>
Paste as HTML:
</p>
<div contenteditable class="editor">
</div>
因此,正如您在这里看到的,剪贴板中保存了一些与"复制我"完全不同的内容,根据您是将其"粘贴"到<textarea>
还是contenteditable
,您将获得相应的数据.
如果您将其"粘贴"到不同的应用程序中,情况也是如此(对于许多应用程序和操作系统).如果你"正常"地将其粘贴为RTE,它将使用HTML版本,或者如果你 Select "粘贴为纯文本"或"粘贴并匹配样式",则将使用"文本/纯文本".如果不存在"文本/纯文本",则由执行粘贴的应用程序决定如何格式化它.
所以,如果你想让纯文本保持一致,你可以使用html
,然后用你自己的转换后的文本覆盖text/plain
.
function copyListener(event) {
const range = window.getSelection().getRangeAt(0);
const rangeContents = range.cloneContents();
const wrapper = document.createElement('div')
wrapper.appendChild(rangeContents);
// store the actual HTML for rich text editors
event.clipboardData.setData("text/html", wrapper.innerHTML);
// store some custome plain text
event.clipboardData.setData("text/plain", 'my custom plain text');
event.preventDefault();
};
document.addEventListener("copy", copyListener, false);
.editor {
width: 30em;
height: 10em;
border: 1px solid rgb(200, 200, 200)
}
<h3>Select and copy these four lines of text</h3>
<div>Paste into the textarea below</div>
<p>There is a blank line after the P element</p>
<h4>What causes this?</h4>
<p>
Paste as Plain:
</p>
<textarea class="editor"></textarea>
<p>
Paste as HTML:
</p>
<div contenteditable class="editor">
</div>