单击按钮复制到剪贴板

新手上路,请多包涵

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

原文由 Dishan TD 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 678
2 个回答

截至 2016 年编辑

自 2016 年起,您现在可以在大多数浏览器中将文本复制到剪贴板,因为大多数浏览器都能够使用 document.execCommand("copy") 以编程方式将所选文本复制到剪贴板,这适用于所选内容。

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

这是一个代码示例:

 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 帖子中找到有关该问题和可能的解决方法的其他讨论:


这些要求使用 Flash 的现代替代方法的问题收到了很多问题的赞成票,但没有解决方案的答案(可能是因为不存在):


Internet Explorer 和 Firefox 曾经有用于访问剪贴板的非标准 API,但它们更现代的版本已经弃用了这些方法(可能出于安全原因)。


有一项 新生的标准努力 试图提出一种“安全”的方法来解决最常见的剪贴板问题(可能需要特定的用户操作,如 Flash 解决方案所需要的),看起来它可能在最新的部分实现Firefox 和 Chrome 版本,但我还没有确认。

原文由 jfriend00 发布,翻译遵循 CC BY-SA 3.0 许可协议

2020 年更新:此解决方案使用 execCommand 。虽然在撰写此答案时该功能还不错, 但现在被认为已过时。它仍然可以在许多浏览器上工作,但不鼓励使用它,因为支持可能会被删除。

还有另一种非 Flash 方式(除了 jfriend00 的回答 中提到的 剪贴板 API 之外)。您需要选择文本,然后 执行命令 copy 将当前在页面上选择的任何文本复制到剪贴板。

例如,此函数会将传递的元素的内容复制到剪贴板(根据 PointZeroTwo 的评论中的建议更新):

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

它是这样工作的:

  1. 创建一个临时隐藏的文本字段。
  2. 将元素的内容复制到该文本字段。
  3. 选择文本字段的内容。
  4. 执行命令副本,如: document.execCommand("copy")
  5. 删除临时文本字段。

注意 元素的内部文本可以包含 空格。因此,如果您想使用 if 作为密码,您可以在上面的代码中使用 $(element).text().trim() 来修剪文本。

你可以在这里看到一个快速演示:

 function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="p1">P1: I am paragraph 1</p>
<p id="p2">P2: I am a second paragraph</p>
<button onclick="copyToClipboard('#p1')">Copy P1</button>
<button onclick="copyToClipboard('#p2')">Copy P2</button>
<br/><br/><input type="text" placeholder="Paste here for test" />

主要问题是目前并非所有 浏览器都支持 此功能,但您可以在以下主要浏览器上使用它:

  • 铬 43
  • 浏览器 10
  • 火狐 41
  • 野生动物园 10

更新 1:这也可以通过纯 JavaScript 解决方案(无 jQuery)来实现:

 function copyToClipboard(elementId) {

  // Create a "hidden" input
  var aux = document.createElement("input");

  // Assign it the value of the specified element
  aux.setAttribute("value", document.getElementById(elementId).innerHTML);

  // Append it to the body
  document.body.appendChild(aux);

  // Highlight its content
  aux.select();

  // Copy the highlighted text
  document.execCommand("copy");

  // Remove it from the body
  document.body.removeChild(aux);

}
 <p id="p1">P1: I am paragraph 1</p>
<p id="p2">P2: I am a second paragraph</p>
<button onclick="copyToClipboard('p1')">Copy P1</button>
<button onclick="copyToClipboard('p2')">Copy P2</button>
<br/><br/><input type="text" placeholder="Paste here for test" />

请注意,我们现在传递没有 # 的 id。

正如 madzohan 在下面的评论中所报告的那样,在某些情况下(在本地运行文件),64 位版本的 Google Chrome 存在一些奇怪的问题。上面的非 jQuery 解决方案似乎解决了这个问题。

Madzohan 在 Safari 中尝试过,解决方案有效,但使用 document.execCommand('SelectAll') 而不是使用 .select() (如聊天和下面的评论中所指定)。

正如 PointZeroTwo 在评论中指出的那样, 可以改进代码,使其返回成功/失败结果。你可以在 这个 jsFiddle 上看到一个演示。


更新:复制保持文本格式

正如一位 用户在西班牙语版的 StackOverflow 中指出的那样, 如果您想按字面复制元素的内容,上面列出的解决方案可以完美地工作,但如果您想粘贴带有格式的复制文本(如它被复制到 input type="text" 中,格式为“丢失”)。

一个解决方案是复制到可编辑的内容 div 然后以类似的方式使用 execCommand 复制它。这里有一个例子——点击复制按钮,然后粘贴到下面的内容可编辑框中:

 function copy(element_id){
  var aux = document.createElement("div");
  aux.setAttribute("contentEditable", true);
  aux.innerHTML = document.getElementById(element_id).innerHTML;
  aux.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");
  document.body.appendChild(aux);
  aux.focus();
  document.execCommand("copy");
  document.body.removeChild(aux);
}
 #target {
  width:400px;
  height:100px;
  border:1px solid #ccc;
}
 <p id="demo"><b>Bold text</b> and <u>underlined text</u>.</p>
<button onclick="copy('demo')">Copy Keeping Format</button>

<div id="target" contentEditable="true"></div>

在 jQuery 中,它会是这样的:

 function copy(selector){
  var $temp = $("<div>");
  $("body").append($temp);
  $temp.attr("contenteditable", true)
       .html($(selector).html()).select()
       .on("focus", function() { document.execCommand('selectAll',false,null); })
       .focus();
  document.execCommand("copy");
  $temp.remove();
}
 #target {
  width:400px;
  height:100px;
  border:1px solid #ccc;
}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p id="demo"><b>Bold text</b> and <u>underlined text</u>.</p>
<button onclick="copy('#demo')">Copy Keeping Format</button>

<div id="target" contentEditable="true"></div>

原文由 Alvaro Montoro 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题