document.execCommand('copy') 命令在字符串的开头和结尾添加换行符

NIK*_*C M 5 html javascript dom

我编写了这个函数来将文本复制到剪贴板。它复制内容,但它向复制的字符串添加换行符。

function copyToClipboard(text) {
           // console.log("text",text);
            const textarea = document.createElement('textarea');
            textarea.textContent = text;
            document.body.appendChild(textarea);
            var selection = document.getSelection();
            var range = document.createRange();
            range.selectNode(textarea);
            selection.removeAllRanges();
            selection.addRange(range);
            const success = document.execCommand('copy');
            selection.removeAllRanges();
            document.body.removeChild(textarea);
            return success;
            console.log("now paste in the text area");
        }
        
      $('button').click(function () {
        copyToClipboard($('#ip').val());  
      })
Run Code Online (Sandbox Code Playgroud)
textarea{
width:100%;
height: 200px;
border: 1px solid grey;
}
input{
min-width: 200px;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id='ip' placeholder="insert some text and press copy"><button>Copy</button>
<textarea placeholder='perform paste in this textarea and you will see line feeds'>
</textarea>
Run Code Online (Sandbox Code Playgroud)

如果您运行代码段并按照说明进行操作,您可以在文本区域中看到换行符。

我尝试过的。

我使用下面的代码复制到剪贴板,但由于某种原因它在我的项目中不起作用。但它适用于其他代码库,即使在浏览器控制台中也是如此。它不包含换行符。

function copyToClipBoard2(text) {
  var textArea = document.createElement("textarea");
  textArea.value = text;
  document.body.appendChild(textArea);
  textArea.select();
  var successful = document.execCommand('copy');
  if (successful){
    console.log("copied to clipboard");
  }
  document.body.removeChild(textArea);}
Run Code Online (Sandbox Code Playgroud)

我怎样才能不向复制的文本添加换行符?

Use*_*863 3

问题是使用selectNode

range.selectNode(textarea);
Run Code Online (Sandbox Code Playgroud)

根据文档,将selectNode父节点设置为范围开始

Range.selectNode() 方法设置 Range 以包含 Node 及其内容。Range 的开始和结束的父节点将与引用节点的父节点相同。

如果你不能使用select(),那么尝试使用setSelectionRange()

range.selectNode(textarea);
Run Code Online (Sandbox Code Playgroud)
function copyToClipboard(text) {
  const textarea = document.createElement('textarea');
  textarea.textContent = text;
  document.body.appendChild(textarea);
  textarea.focus();
  textarea.setSelectionRange(0, -1);
  const success = document.execCommand('copy');
  document.body.removeChild(textarea);
  return success;
}

$('button').click(function() {
  copyToClipboard($('#ip').val());
})
Run Code Online (Sandbox Code Playgroud)
textarea {
  width: 100%;
  height: 200px;
  border: 1px solid grey;
}

input {
  min-width: 200px;
}
Run Code Online (Sandbox Code Playgroud)

备择方案