如何将div内的文本复制到剪贴板?我有一个div,需要添加一个链接,将文本添加到剪贴板。有解决办法吗?

<p class="content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p>

<a class="copy-text">copy Text</a>

在我点击复制文本,然后我按Ctrl + V,它必须被粘贴。


当前回答

下面是多个答案的组合。这将正确地保存换行符。

// Copies a value to the clipboard
    window.copyToClipboard = function(value) {
        // navigator clipboard api needs a secure context (https)
        if (navigator.clipboard && window.isSecureContext) {
            // navigator clipboard api method
            return navigator.clipboard.writeText(value).then(function () {
                //alert('It worked! Do a CTRL - V to paste')
            }, function () {
                alert('Error while copying to clipboard.')
            });
        } else {
            // text area method
            let textArea = document.createElement("textarea");
            textArea.value = value;
            // make the textarea out of viewport
            textArea.style.position = "fixed";
            textArea.style.left = "-999999px";
            textArea.style.top = "-999999px";
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            document.execCommand('copy');
            textArea.remove();
        }
    }

其他回答

你可以使用这个库轻松实现复制目标!

https://clipboardjs.com/

将文本复制到剪贴板应该不难。它不需要 数十个配置步骤或数百kb的加载。但是大部分 总之,它不应该依赖于Flash或任何膨胀的框架。 这就是clipboard.js存在的原因。

or

https://github.com/zeroclipboard/zeroclipboard

http://zeroclipboard.org/

ZeroClipboard库提供了一种简单的方法来将文本复制到 剪贴板使用一个不可见的Adobe Flash电影和JavaScript 接口。

2023年1月

从2023年开始,你应该使用剪贴板Api。

navigator.clipboard.writeText('text here you want to copy').then(function () {
    alert('It worked! Do a CTRL - V to paste')
}, function () {
    alert('Failure to copy. Check permissions for clipboard')
});

这里是关于与剪贴板交互的更多信息

换行(阿尔瓦罗·蒙托罗回答的延伸)

var ClipboardHelper = {

    copyElement: function ($element)
    {
       this.copyText($element.text())
    },
    copyText:function(text) // Linebreaks with \n
    {
        var $tempInput =  $("<textarea>");
        $("body").append($tempInput);
        $tempInput.val(text).select();
        document.execCommand("copy");
        $tempInput.remove();
    }
};

ClipboardHelper.copyText('Hello\nWorld');
ClipboardHelper.copyElement($('body h1').first());

js是一个很好的实用工具,它允许在不使用Flash的情况下将文本或HTML数据复制到剪贴板。它很容易使用;只需要包含.js并使用如下代码:

<button id='markup-copy'>Copy Button</button>

<script>
    document.getElementById('markup-copy').addEventListener('click', function() {
        clipboard.copy({
            'text/plain': 'Markup text. Paste me into a rich text editor.',
            'text/html': '<i>here</i> is some <b>rich text</b>'
        }).then(
            function(){console.log('success'); },
            function(err){console.log('failure', err);
        });
    });
</script>

clipboard.js也在GitHub上。

2016年1月15日编辑:今天编辑了顶部的答案,引用了我在2015年8月发布的答案中的相同API。前面的文本指示用户使用ZeroClipboard。只是想澄清一下,我并没有从jfriend00的答案中抽取这个,而是相反。

function copyToClipboard(element) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($('span[id='+element+']').text()).select();
    document.execCommand("copy");
    $temp.remove();
}