复制文档到剪切板中空格,换行等会丢失的问题

之前处理了fetch流的问题的时候,后端返回的流是含有空格、换行等内容的,然后要将这个流复制到剪切板中。就发现空格丢失部分,换行全部丢失了 发现问题解决问题,就去找为什么复制到剪切板中空格、换行会丢失。

 

 let content='   a b c d 
            d e f ^'//包含换行,空格等样式
var input = document.createElement("input");
document.body.appendChild(input);
input.setAttribute("value", content);
input.select();
if (document.execCommand("copy")) {
  document.execCommand("copy");
}
document.body.removeChild(input);

后来发现是用   document.createElement("input")  的原因,这是因为input框中的内容不包含换行,换行后的空格也不会写进去。所以就换了一种方式来写,将input换成textarea,因为textarea 是一个多行的文本输入控件,支持空格,换行等样式的存在的。

let content='   a b c d 
            d e f ^'//包含换行,空格等样式
var tempInput = document.createElement("textarea");
document.body.appendChild(tempInput);
tempInput.value = content;
tempInput.select();
document.execCommand("copy");
document.body.removeChild(tempInput);

问题成功解决了。

 

posted @ 2023-05-26 17:09  NicoleYe  阅读(334)  评论(0)    收藏  举报