点击button复制到剪贴板使用jQuery

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

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

编辑截至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"> 

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

例如,这个函数将把传入的元素的内容复制到剪贴板(在PointZeroTwo的注释中用build议更新):

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

这是如何工作的:

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

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

 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" /> 

clipboard.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的回答中抽出这个,而是反过来。

断线(从Alvaro Montoro解答)

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

更好的方法没有闪光或任何其他要求是clipboard.js 。 您只需在任意button上添加data-clipboard-target="#toCopyElement" ,将其初始化为new Clipboard('.btn'); data-clipboard-target="#toCopyElement" new Clipboard('.btn'); 它会将DOM的内容复制到剪贴板toCopyElement 。 这是通过链接复制问题中提供的文本的片段。

一个限制,虽然它不适用于Safari浏览器,但它适用于所有其他浏览器,包括移动浏览器,因为它不使用闪光灯

 $(function(){ new Clipboard('.copy-text'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js"></script> <p id="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" data-clipboard-target="#content" href="#">copy Text</a> 

这是复制内容最简单的方法

  <div id="content"> Lorepm ispum </div> <button class="copy" title="content">Copy Sorce</button> function SelectContent(element) { var doc = document , text = doc.getElementById(element) , range, selection ; if (doc.body.createTextRange) { range = document.body.createTextRange(); range.moveToElementText(text); range.select(); } else if (window.getSelection) { selection = window.getSelection(); range = document.createRange(); range.selectNodeContents(text); selection.removeAllRanges(); selection.addRange(range); } document.execCommand('Copy'); } $(".copy").click(function(){ SelectContent( $(this).attr('title')); }); 

要复制的文本是在文本input,如: <input type="text" id="copyText" name="copyText">并在button上单击上面的文本应复制到剪贴板,所以button是: <button type="submit" id="copy_button" data-clipboard-target='copyText'>Copy</button>你的脚本应该是这样的:

 <script language="JavaScript"> $(document).ready(function() { var clip = new ZeroClipboard($("#copy_button"), { moviePath: "ZeroClipboard.swf" }); }); </script> 

对于CDN文件

  • (zeroclipboard.swf) :
  • (zeroclipboard.js) :

注意ZeroClipboard.swfZeroClipboard.js文件应该和你的文件在同一个文件夹中,或者你必须在我们的页面上包含<script src=""></script>

 <!DOCTYPE html> <html> <head> <title></title> <link href="css/index.css" rel="stylesheet" /> <script src="js/jquery-2.1.4.min.js"></script> <script> function copy() { try { $('#txt').select(); document.execCommand('copy'); } catch(e) { alert(e); } } </script> </head> <body> <h4 align="center">Copy your code</h4> <textarea id="txt" style="width:100%;height:300px;"></textarea> <br /><br /><br /> <div align="center"><span class="btn-md" onclick="copy();">copy</span></div> </body> </html> 

你可以使用这个lib来实现复制目标!

https://clipboardjs.com/

复制文本到剪贴板应该不难。 它不需要几十个步骤来configuration或加载数百个KB。 但最重要的是,它不应该依赖于Flash或任何臃肿的框架。

这就是为什么clipboard.js存在。

要么

https://github.com/zeroclipboard/zeroclipboard

http://zeroclipboard.org/

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

html代码在这里

  <input id="result" style="width:300px"/>some example text <button onclick="copyToClipboard('result')">Copy P1</button> <input type="text" style="width:400px" placeholder="Paste here for test" /> 

JS代码:

  function copyToClipboard(elementId) { // Create a "hidden" input var aux = document.createElement("input"); aux.setAttribute("value", document.getElementById(elementId).value); // 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); } 
 <div class="form-group"> <label class="font-normal MyText">MyText to copy</label>&nbsp; <button type="button" class="btn btn-default btn-xs btnCopy" data="MyText">Copy</button> </div> $(".btnCopy").click(function () { var element = $(this).attr("data"); copyToClipboard($('.' + element)); }); function copyToClipboard(element) { var $temp = $("<input>"); $("body").append($temp); $temp.val($(element).text()).select(); document.execCommand("copy"); $temp.remove(); }