[英]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.