如何防止javascript复制换行到剪贴板?



我发现了一个程序,它允许我将数据从div复制到剪贴板。当复制时,它会添加一个换行符,即使在我的div中没有换行符。我如何从副本中删除任何换行符?

function copyDivToClipboard(elem) {
var range = document.createRange();
range.selectNode(document.getElementById(elem));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand("copy");
window.getSelection().removeAllRanges();

}
<div id='test'>This is a test</div>
<button onclick='copyDivToClipboard("test")'>Copy to clipboard</button>

range.selectNodeContents代替range.selectNode

function copyDivToClipboard(elem) {
var range = document.createRange();
range.selectNodeContents(document.getElementById(elem));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand("copy");
window.getSelection().removeAllRanges();
}
<div id="test">
This is a test
</div>
<button onclick='copyDivToClipboard("test")'>Copy to clipboard</button>

您正在复制的div元素包含换行符作为其文本内容的一部分,当Javascript正在复制它。如果您使用span,您将无法获得带有文本的换行符。

https://jsfiddle.net/sLv9ux50/

您还可以为document.selection添加回退,并在完成后执行回调函数。

function copy_to_clipboard (containerid = '', cb = () => {}) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(containerid));
range.select().createTextRange();
document.execCommand("copy");
cb();
} else if (window.getSelection) {
const selection = window.getSelection();
selection.removeAllRanges();
var range = document.createRange();
var node = document.getElementById(containerid);
range.selectNodeContents(node);
selection.addRange(range);
document.execCommand("copy");
selection.removeAllRanges();
cb();
}
}