单击按钮使用jQuery复制到剪贴板

卫骏
2023-12-01

本文翻译自:Click button copy to clipboard using jQuery

How do I copy the text inside a div to the clipboard? 如何将div中的文本复制到剪贴板? I have a div and need to add a link which will add the text to the clipboard. 我有一个div,需要添加一个链接,该链接会将文本添加到剪贴板。 Is there a solution for this? 有解决方案吗?

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

After I click copy text, then I press Ctrl + V , it must be pasted. 单击复制文本后,然后按Ctrl + V ,必须将其粘贴。


#1楼

参考:https://stackoom.com/question/1WkRF/单击按钮使用jQuery复制到剪贴板


#2楼

Edit as of 2016 截至2016年编辑

As of 2016, you can now copy text to the clipboard in most browsers because most browsers have the ability to programmatically copy a selection of text to the clipboard using document.execCommand("copy") that works off a selection. 从2016年开始,您现在可以在大多数浏览器中将文本复制到剪贴板,因为大多数浏览器都可以使用可以关闭选择内容的document.execCommand("copy")以编程方式将文本的选择复制到剪贴板。

As with some other actions in a browser (like opening a new window), the copy to clipboard can only be done via a specific user action (like a mouse click). 与浏览器中的某些其他操作(例如,打开新窗口)一样,只能通过特定的用户操作(例如,单击鼠标)将内容复制到剪贴板。 For example, it cannot be done via a timer. 例如,它不能通过计时器来完成。

Here's a code example: 这是一个代码示例:

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


Here's a little more advanced demo: https://jsfiddle.net/jfriend00/v9g1x0o6/ 这是一个更高级的演示: https : //jsfiddle.net/jfriend00/v9g1x0o6/

And, you can also get a pre-built library that does this for you with clipboard.js . 而且,你还可以得到一个预建库,以做到这一点你clipboard.js


Old, historical part of answer 答案的历史部分

Directly copying to the clipboard via JavaScript is not permitted by any modern browser for security reasons. 出于安全原因,任何现代浏览器均不允许通过JavaScript直接复制到剪贴板。 The most common workaround is to use a Flash capability for copying to the clipboard that can only be triggered by a direct user click. 最常见的解决方法是使用Flash功能将其复制到剪贴板,这只能由用户直接单击触发。

As mentioned already, ZeroClipboard is a popular set of code for managing the Flash object to do the copy. 如前所述, ZeroClipboard是用于管理Flash对象进行复制的常用代码集。 I've used it. 我用过了 If Flash is installed on the browsing device (which rules out mobile or tablet), it works. 如果在浏览设备上安装了Flash(排除了移动设备或平板电脑),则它可以正常工作。


The next most common work-around is to just place the clipboard-bound text into an input field, move the focus to that field and advise the user to press Ctrl + C to copy the text. 下一个最常见的解决方法是将剪贴板上的文本放置到输入字段中,将焦点移到该字段上,并建议用户按Ctrl + C来复制文本。

Other discussions of the issue and possible work-arounds can be found in these prior Stack Overflow posts: 可以在以下先前的Stack Overflow帖子中找到有关该问题的其他讨论以及可能的解决方法:


These questions asking for a modern alternative to using Flash have received lots of question upvotes and no answers with a solution (probably because none exist): 这些要求使用Flash的现代替代方法的问题已经收到很多问题的投票,而没有解决方案的答案(可能是因为不存在):


Internet Explorer and Firefox used to have non-standard APIs for accessing the clipboard, but their more modern versions have deprecated those methods (probably for security reasons). Internet Explorer和Firefox曾经具有用于访问剪贴板的非标准API,但它们的较新版本已弃用了这些方法(可能出于安全原因)。


There is a nascent standards effort to try to come up with a "safe" way to solve the most common clipboard problems (probably requiring a specific user action like the Flash solution requires), and it looks like it may be partially implemented in the latest versions of Firefox and Chrome, but I haven't confirmed that yet. 正在进行一项新的标准工作 ,试图提出一种“安全”的方法来解决最常见的剪贴板问题(可能需要特定的用户操作,如Flash解决方案所要求的),并且看起来它可能是在最新版本中部分实现的版本的Firefox和Chrome,但我尚未确认。


#3楼

The text to copy is in text input,like: <input type="text" id="copyText" name="copyText"> and, on button click above text should get copied to clipboard,so button is like: <button type="submit" id="copy_button" data-clipboard-target='copyText'>Copy</button> Your script should be like: 要复制的文本在文本输入中,例如: <input type="text" id="copyText" name="copyText">并且在按钮上单击上方的文本应将其复制到剪贴板,因此按钮类似于: <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>

For CDN files 对于CDN文件

note : ZeroClipboard.swf and ZeroClipboard.js " file should be in the same folder as your file using this functionality is, OR you have to include like we include <script src=""></script> on our pages. 注意 :使用此功能后, ZeroClipboard.swfZeroClipboard.js文件应与文件位于同一文件夹中,或者您必须像在页面上添加<script src=""></script>一样包含。


#4楼

There is another non-Flash way (apart from the Clipboard API mentioned in jfriend00's answer ). 还有另一种非Flash方式(除了jfriend00的答案中提到的Clipboard API )。 You need to select the text and then execute the command copy to copy to the clipboard whatever text is currently selected on the page. 您需要选择文本,然后执行命令copy以将页面上当前选择的任何文本复制到剪贴板。

For example, this function will copy the content of the passed element into the clipboard (updated with suggestion in the comments from PointZeroTwo ): 例如,此函数会将传递的元素的内容复制到剪贴板(根据PointZeroTwo的注释中的建议进行更新):

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

This is how it works: 它是这样工作的:

  1. Creates a temporary hidden text field. 创建一个临时的隐藏文本字段。
  2. Copies the content of the element to that text field. 将元素的内容复制到该文本字段。
  3. Selects the content of the text field. 选择文本字段的内容。
  4. Executes the command copy like: document.execCommand("copy") . 执行命令副本,例如: document.execCommand("copy")
  5. Removes the temporary text field. 删除临时文本字段。

You can see a quick demo here: 您可以在此处查看快速演示:

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

The main issue is that not all browsers support this feature at the moment, but you can use it on the main ones from: 主要问题是,目前并非所有浏览器都支持此功能,但您可以从以下主要途径使用它:

  • Chrome 43 镀铬43
  • Internet Explorer 10 Internet Explorer 10
  • Firefox 41 Firefox 41
  • Safari 10 Safari 10

Update 1: This can be achieved also with a pure JavaScript solution (no jQuery): 更新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" /> 

Notice that we pass the id without the # now. 请注意,我们传递的ID现在没有#号。

As madzohan reported in the comments below, there is some strange issue with the 64-bit version of Google Chrome in some cases (running the file locally). 正如madzohan在以下评论中所报告的那样,在某些情况下(本地运行文件),64位版本的Google Chrome浏览器存在一些奇怪的问题。 This issue seems to be fixed with the non-jQuery solution above. 上面的非jQuery解决方案似乎已解决了该问题。

Madzohan tried in Safari and the solution worked but using document.execCommand('SelectAll') instead of using .select() (as specified in the chat and in the comments below). Madzohan在Safari中进行了尝试,该解决方案有效,但使用了document.execCommand('SelectAll')而不是.select() (如聊天室和以下注释中所指定)。

As PointZeroTwo points out in the comments , the code could be improved so it would return a success/failure result. 正如PointZeroTwo在注释中指出的那样,可以改进代码,以便返回成功/失败结果。 You can see a demo on this jsFiddle . 您可以在此jsFiddle上看到一个演示。


UPDATE: COPY KEEPING THE TEXT FORMAT 更新:保留文本格式

As a user pointed out in the Spanish version of StackOverflow , the solutions listed above work perfectly if you want to copy the content of an element literally, but they don't work that great if you want to paste the copied text with format (as it is copied into a input type="text" , the format is "lost"). 正如用户在西班牙语版本的StackOverflow中指出的那样,上面列出的解决方案如果您想按字面意义复制元素的内容,则可以完美地工作,但是,如果您想将复制的文本粘贴为格式(如将其复制到input type="text" ,格式为“ lost”)。

A solution for that would be to copy into a content editable div and then copy it using the execCommand in a similar way. 一种解决方案是将其复制到内容可编辑的div ,然后以类似方式使用execCommand复制它。 Here there is an example - click on the copy button and then paste into the content editable box below: 这里有一个例子-单击复制按钮,然后粘贴到下面的内容可编辑框中:

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> 

And in jQuery, it would be like this: 在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> 


#5楼

clipboard.js is a nice utility that allows copying of text or HTML data to the clipboard without use of Flash. 剪贴板.js是一个很好的实用程序,它允许在不使用Flash的情况下将文本或HTML数据复制到剪贴板。 It's very easy to use; 它很容易使用; just include the .js and use something like this: 只需包含.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 is also on GitHub . Clipboard.js也位于GitHub上

Edit on Jan 15, 2016: The top answer was edited today to reference the same API in my answer posted in August 2015. The previous text was instructing users to use ZeroClipboard. 2016年1月15日修改:今天,对最高答案进行了编辑 ,以在我于2015年8月发布的答案中引用相同的API。之前的内容是指示用户使用ZeroClipboard。 Just want to be clear that I didn't yank this from jfriend00's answer, rather the other way around. 只是想清楚一点,我并没有从jfriend00的答案中得出这个结论,反之亦然。


#6楼

It is a simplest method to copy the content 这是复制内容的最简单方法

 <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'));
                    });
 类似资料: