[英]How to put some text to clipboard using javaScript?
我想讓用戶將某些內容復制到剪貼板。 我嘗試了以下方法。
var textArea = document.createElement('textarea');
textArea.textContent = response['file_content'];
document.body.appendChild(textArea);
var selection = document.getSelection();
var range = document .createRange();
range.selectNode(textArea)
selection.removeAllRanges();
selection.addRange(range);
if(document.execCommand('copy'))
{
console.log('Template copied to clipboard');
}else {
console.log('Copying Failed');
}
selection.removeAllRanges();
document.body.removeChild(textArea)
但不幸的是
document.execCommand('copy')
在Chrome 68和Mozilla Firefox 60中總是返回false。在IE 11中似乎可以正常工作。我已經在SO上遇到了很多類似的問題,但是,這些都不適合我。 我不想使用閃光燈。
我在項目中使用了以下代碼。它為我工作。
元件
<a rel="tooltip" data-placement="top" title="Copy code" class="copytext-btn copyText" href="javascript:void(0);"><i class="code-file-icn"></i></a>
ClickEvent:
jQuery(".copyText").click(function(e)
{
e.preventDefault();
copyTextToClipboard(jQuery('.GeneratedText').text());
});
功能:
function copyTextToClipboard(text)
{
var textArea = document.createElement("textarea");
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
try {
var successful = document.execCommand('copy');
if(successful)
{
// SuccessCode
}
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
}
catch (err)
{
console.log('Oops, unable to copy');
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.