如何使用javaScript将一些文本放到剪贴板中?

问题描述 投票:0回答:1

我想让用户将一些内容复制到剪贴板。我尝试了以下内容。

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上经历了很多类似的问题,但这一切对我都不起作用。我不想使用闪光灯。

javascript jquery google-chrome mozilla
1个回答
7
投票

我在我的项目中使用了以下代码..它为我工作..

元件

<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');
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.