如何将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,它必须被粘贴。


当前回答

 document.getElementById('markup-copy').addEventListener('click', function() {
               var txt = "Your text Here";
                    $("<textarea/>").appendTo("body").val(txt).select().each(function () {
                    document.execCommand('copy');
                }).remove();
            });

其他回答

这是一个优雅的Javascript解决方案

<input type="text" value="Foo Bar" id="your_input">
<button onclick="copy()">Copy text</button>

<script type="application/javascript">
function copy() {
  var copiedtext = document.getElementById("your_input");
  copiedtext.select();
  copiedtext.setSelectionRange(0, 99999); //for mobile devices
  navigator.clipboard.writeText(copiedtext.value);
  alert("You just copied " + copiedtext.value);
}
</script>

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

// 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();
        }
    }

输入字段没有display: none,这一点非常重要。浏览器不会选择文本,因此不会被复制。使用不透明度:0,宽度为0px来解决这个问题。

编辑截止2016年

截至2016年,您现在可以在大多数浏览器中将文本复制到剪贴板,因为大多数浏览器都能够使用document.execCommand(“复制”)以编程方式将所选文本复制到剪贴板。

与浏览器中的其他一些操作(如打开一个新窗口)一样,复制到剪贴板只能通过特定的用户操作(如鼠标单击)来完成。例如,它不能通过计时器来完成。

下面是一个代码示例:

document.getElementById("copyButton").addEventListener("click", function() { copyToClipboard(document.getElementById("copyTarget")); }); function copyToClipboard(elem) { // create hidden text element, if it doesn't already exist var targetId = "_hiddenCopyText_"; var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA"; var origSelectionStart, origSelectionEnd; if (isInput) { // can just use the original source element for the selection and copy target = elem; origSelectionStart = elem.selectionStart; origSelectionEnd = elem.selectionEnd; } else { // must use a temporary form element for the selection and copy target = document.getElementById(targetId); if (!target) { var target = document.createElement("textarea"); target.style.position = "absolute"; target.style.left = "-9999px"; target.style.top = "0"; target.id = targetId; document.body.appendChild(target); } target.textContent = elem.textContent; } // select the content var currentFocus = document.activeElement; target.focus(); target.setSelectionRange(0, target.value.length); // copy the selection var succeed; try { succeed = document.execCommand("copy"); } catch(e) { succeed = false; } // restore original focus if (currentFocus && typeof currentFocus.focus === "function") { currentFocus.focus(); } if (isInput) { // restore prior selection elem.setSelectionRange(origSelectionStart, origSelectionEnd); } else { // clear temporary content target.textContent = ""; } return succeed; } input { width: 400px; } <input type="text" id="copyTarget" value="Text to Copy"> <button id="copyButton">Copy</button><br><br> <input type="text" placeholder="Click here and press Ctrl-V to see clipboard contents">


这里有一个更高级的演示:https://jsfiddle.net/jfriend00/v9g1x0o6/

你也可以用clipboard.js获得一个预构建的库来做这个。


古老的,历史的答案

由于安全原因,任何现代浏览器都不允许通过JavaScript直接复制到剪贴板。最常见的解决方法是使用Flash功能复制到剪贴板,这只能由用户直接单击触发。

如前所述,ZeroClipboard是一组用于管理Flash对象以执行复制的流行代码。我用过。如果Flash安装在浏览设备上(排除了手机或平板电脑),它就能正常工作。


下一个最常见的解决方法是将剪贴板绑定的文本放入一个输入字段,将焦点移到该字段,并建议用户按Ctrl + C复制文本。

关于这个问题的其他讨论和可能的解决方法可以在这些之前的Stack Overflow帖子中找到:

我如何复制到剪贴板在JavaScript? 如何使用jQuery将文本复制到客户端的剪贴板? 如何复制到剪贴板没有Flash?


这些问题询问了使用Flash的现代替代方案,得到了大量的赞,但没有答案(可能是因为根本不存在):

HTML5替代基于flash的ZeroClipboard安全复制数据到剪贴板? 复制到剪贴板没有Flash


Internet Explorer和Firefox曾经使用非标准api来访问剪贴板,但它们的最新版本已经弃用了这些方法(可能是出于安全原因)。


有一种新兴的标准试图提出一种“安全”的方法来解决最常见的剪贴板问题(可能需要特定的用户操作,就像Flash解决方案所要求的那样),看起来它可能会在最新版本的Firefox和Chrome中部分实现,但我还没有证实这一点。

非常简单。你必须搜索js navigator.clipboard.writeText("thistext"); 这将简单地复制文本“thistext”。现在让它工作点击,使用jquery onclick函数和存储值(你想复制的文本)在一个字符串(如果你需要,那么你可以使用DOM以及从页面获取一个值),并使用这一行复制,而不是“thistext”,传递变量!