我已经编写了这个函数来复制文本到剪贴板。它可以复制内容,但会在复制的字符串中添加换行符。
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());
})
textarea{
width:100%;
height: 200px;
border: 1px solid grey;
}
input{
min-width: 200px;
}
<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>
如果您运行代码片段并按照说明操作,则可以在文本区域中看到换行符。
我尝试过的内容。
我使用了以下代码来复制到剪贴板,但由于某些原因,在我的项目中它不起作用。 但它在其他代码库中工作,并且即使在浏览器控制台中也不包含换行符。
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);}
如何避免复制文本时添加换行符?
textarea.select()
呢? - ATP