使用 jQuery 单击按钮复制到剪贴板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22581345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Click button copy to clipboard using jQuery
提问by Dishan TD
How do I copy the text inside a div to the clipboard? I have a div and need to add a link which will add the text to the clipboard. Is there a solution for this?
如何将 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>
After I click copy text, then I press Ctrl+ V, it must be pasted.
单击复制文本后,然后按Ctrl+ V,必须粘贴它。
回答by Alvaro Montoro
There is another non-Flash way (apart from the Clipboard APImentioned in jfriend00's answer). 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.
还有另一种非 Flash 方式(除了jfriend00 的回答中提到的剪贴板 API)。您需要选择文本,然后执行命令将页面上当前选择的任何文本复制到剪贴板。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:
这是它的工作原理:
- Creates a temporary hidden text field.
- Copies the content of the element to that text field.
- Selects the content of the text field.
- Executes the command copy like:
document.execCommand("copy")
. - Removes the temporary text field.
- 创建一个临时隐藏的文本字段。
- 将元素的内容复制到该文本字段。
- 选择文本字段的内容。
- 执行命令复制,如:
document.execCommand("copy")
。 - 删除临时文本字段。
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 supportthis feature at the moment, but you can use it on the main ones from:
主要问题是目前并非所有浏览器都支持此功能,但您可以在以下主要浏览器上使用它:
- Chrome 43
- Internet Explorer 10
- Firefox 41
- Safari 10
- 铬 43
- 浏览器 10
- 火狐 41
- 野生动物园 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 madzohanreported in the comments below, there is some strange issue with the 64-bit version of Google Chrome in some cases (running the file locally). This issue seems to be fixed with the non-jQuery solution above.
正如madzohan在下面的评论中所报告的那样,在某些情况下(在本地运行文件),64 位版本的 Google Chrome 存在一些奇怪的问题。上面的非 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. You can see a demo on this jsFiddle.
正如PointZeroTwo 在评论中指出的那样,可以改进代码,使其返回成功/失败结果。你可以在这个 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"
,格式“丢失”)。
A solution for that would be to copy into a content editable div
and then copy it using the execCommand
in a similar way. Here there is an example - click on the copy button and then paste into the content editable box below:
一个解决方案是复制到可编辑的内容中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>
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>
回答by jfriend00
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. 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.
出于安全原因,任何现代浏览器都不允许通过 JavaScript 直接复制到剪贴板。最常见的解决方法是使用 Flash 功能复制到剪贴板,该功能只能由用户直接单击触发。
As mentioned already, ZeroClipboardis a popular set of code for managing the Flash object to do the copy. I've used it. If Flash is installed on the browsing device (which rules out mobile or tablet), it works.
如前所述,ZeroClipboard是一组流行的代码,用于管理 Flash 对象以进行复制。我用过。如果浏览设备(排除手机或平板电脑)上安装了 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+ Cto 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 effortto 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 的版本,但我还没有确认。
回答by a coder
clipboard.jsis a nice utility that allows copying of text or HTML data to the clipboard without use of Flash. It's very easy to use; just include the .js and use something like this:
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 is also on GitHub.
Edit on Jan 15, 2016: The top answerwas editedtoday to reference the same API in my answer posted in August 2015. The previous text was instructing users to use ZeroClipboard. Just want to be clear that I didn't yank this from jfriend00's answer, rather the other way around.
2016 年 1 月 15 日编辑:今天编辑了最重要的答案,以引用我在 2015 年 8 月发布的答案中的相同 API。之前的文字是指导用户使用 ZeroClipboard。只是想明确一点,我没有从 jfriend00 的回答中提取这个,而是反过来。
回答by Nadav
Simplicity is the ultimate sophistication.
If you don't want the text-to-be-coppied to be visible:
jQuery:
简单是终极的精致。
如果您不希望要复制的文本可见:
jQuery:
$('button.copyButton').click(function(){
$(this).siblings('input.linkToCopy').select();
document.execCommand("copy");
});
HTML:
HTML:
<button class="copyButton">click here to copy</button>
<input class="linkToCopy" value="TEXT TO COPY"
style="position: absolute; z-index: -999; opacity: 0;" />
回答by David from Studio.201
With Line Breaks (Extention of the Answer from Alvaro Montoro)
带换行符(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());
回答by keivan kashani
You can use this code for copy input value in page in Clipboard by click a button
您可以使用此代码通过单击按钮在剪贴板中的页面中复制输入值
This is Html
这是 HTML
<input type="text" value="xxx" id="link" class="span12" />
<button type="button" class="btn btn-info btn-sm" onclick="copyToClipboard('#link')">
Copy Input Value
</button>
Then for this html , we must use this JQuery Code
那么对于这个 html ,我们必须使用这个 JQuery 代码
function copyToClipboard(element) {
$(element).select();
document.execCommand("copy");
}
This is the simplest solution for this question
这是这个问题最简单的解决方案
回答by Amgad
Even better approach without flash or any other requirements is clipboard.js. All you need to do is add data-clipboard-target="#toCopyElement"
on any button, initialize it new Clipboard('.btn');
and it will copy the content of DOM with id toCopyElement
to clipboard. This is a snippet that copy the text provided in your question via a link.
没有 flash 或任何其他要求的更好方法是clipboard.js。你需要做的就是添加data-clipboard-target="#toCopyElement"
任何按钮,初始化它new Clipboard('.btn');
,它会将带有 id 的 DOM 内容复制toCopyElement
到剪贴板。这是通过链接复制问题中提供的文本的片段。
One limitation though is that it does not work on safari, but it works on all other browser including mobile browsers as it does not use flash
一个限制是它不适用于 safari,但它适用于所有其他浏览器,包括移动浏览器,因为它不使用 Flash
$(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>
回答by Ujjwal Kumar Gupta
<!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>
回答by Nayan Hodar
<div class="form-group">
<label class="font-normal MyText">MyText to copy</label>
<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();
}
回答by Mark Lancaster
It's very important that the input field does not have display: none
. The browser will not select the text and therefore will not be copied. Use opacity: 0
with a width of 0px to fix the problem.
输入字段没有display: none
. 浏览器不会选择文本,因此不会被复制。使用opacity: 0
宽度为 0px 来解决问题。