本文翻译自: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帖子中找到有关该问题的其他讨论以及可能的解决方法:

  • How do I copy to the clipboard in JavaScript? 如何使用JavaScript复制到剪贴板?

  • How to copy text to the client's clipboard using jQuery? 如何使用jQuery将文本复制到客户端的剪贴板?

  • How can you copy to clipboard without Flash? 没有Flash,如何复制到剪贴板?


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的现代替代方法的问题已经收到很多问题的投票,而没有解决方案的答案(可能是因为不存在):

  • HTML5 alternative to flash-based ZeroClipboard for safe copying of data to clipboard? HTML5替代基于Flash的ZeroClipboard,可将数据安全复制到剪贴板吗?

  • Copy to clipboard without Flash 复制到剪贴板而不使用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文件

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

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'));});

单击按钮使用jQuery复制到剪贴板相关推荐

  1. 如何使用 JavaScript 将文本复制到剪贴板?

    异步剪贴板 API 构建网站时一个非常普遍的需求是能够通过单击按钮将文本复制到剪贴板.如果您只需要支持现代浏览器,强烈建议使用异步剪贴板 API.它在所有现代浏览器中都受支持,并提供了一种简单安全的方 ...

  2. 【转】js实现复制到剪贴板功能,兼容所有浏览器

    2019独角兽企业重金招聘Python工程师标准>>> 两天前听了一个H5的分享,会议上有一句话,非常有感触:不是你不能,而是你对自己的要求太低.很简单的一句话,相信很多事情不是大家 ...

  3. 将所有行复制到剪贴板

    有没有办法在VI编辑器中将所有行从打开文件复制到剪贴板. 我试图ÿg,但它不使用剪贴板来存储这些行. 那有可能吗? #1楼 :%ya所有内容放入vim的缓冲区,在命令模式下按p将在您光标当前所在的行之 ...

  4. html5 复制到剪贴板 兼容,JS实现复制内容到剪贴板功能兼容所有浏览器(推荐)

    两天前听了一个H5的分享,会议上有一句话,非常有感触:不是你不能,而是你对自己的要求太低.很简单的一句话,相信很多事情不是大家做不到,真的是对自己的要求太低,如果对自己要求多一点,那么你取得的进步可能 ...

  5. 禁用剪贴板html如何复制,如何在按钮单击时将干净的HTML复制到剪贴板?

    我想单击按钮时将图像复制到剪贴板,但是当我粘贴它时,它始终有我想要删除的style="...".如何在按钮单击时将干净的HTML复制到剪贴板? function copy(sele ...

  6. html5 复制到剪贴板 兼容,js/jQuery实现复制到剪贴板功能,兼容所有浏览器

    因为工作的原因,需要实现这样一个功能:点击按钮,复制文本内容. 百度了一下,大都语焉不详,最终找到了一篇很好的博文,有讲解,有实例,捣鼓了一会,最终实现了功能. 网址在这里http://www.cnb ...

  7. javascript : 点击按钮,把某标签中的内容复制到剪贴板

    需求如题. 静态页面如下. 需要的库:jquery(不用应该也能做). 浏览器:PC chrome 68 Mobile MIUI9.5(Android 7) <p>1.用电脑打开网址:&l ...

  8. 点击按钮自动复制到剪贴板的实现

    应用场景:你可以在网页上放置文字,在点击文字后你就可以将文字所带的url复制到剪贴板,然后就可以复制到你想到的任何地方. 购票链接:<a href="javascript:void(0 ...

  9. 如何在Vim中复制到剪贴板?

    是否可以直接从Vim复制到剪贴板? yy只复制东西给Vim的内部缓冲区. 我想复制到操作系统的剪贴板. 在Vim中有没有这样的命令,或者你只能在Vim中猛拉东西? #1楼 在vimrc文件中,您可以指 ...

最新文章

  1. 医学影像阅读/分析软件FSLeyes安装避坑+核磁共振影像数据处理
  2. 细胞内钾多钠少——原初生物的第三大遗迹?
  3. 刚从阿里面试回来已拿到offer想和大家分享一下(阿里面试经验)
  4. Firewalld防火墙应用
  5. 使用 Autofac 进行依赖注入
  6. swift. 扩展类添加属性_Swift快速为类扩展属性
  7. 我比领导小15岁,互相有好感,为什么每次路过我办公室都叹气?
  8. UOJ14 UER #1 DZY Loves Graph(最小生成树+并查集)
  9. 使用bintray-release工具上传gradle项目至bintray.com
  10. ansible、ansible tower的安装以及基本使用
  11. java滚动字幕实训报告_Java实习报告 (7000字).doc
  12. 显卡、GPU和CUDA的概念整理
  13. 工作组计算机设置网络密码,设置访问工作组计算机需要密码问题
  14. 海贼王热血航线正在连接服务器,海贼王热血航线为什么连接不了服务器?老是说人已满进不去?...
  15. 用shell脚本写的一个简单的计算器
  16. NNDL 作业4:第四章课后题
  17. JVM简笔—类的加载
  18. 使用ShaderGraph制作漩涡消散效果
  19. ubuntu安装NVIDIA显卡驱动(简单有效)
  20. 前端学习之路CSS基础学习二

热门文章

  1. 如何选择适合企业的软文推广平台?
  2. 基于SSM的便利店系统
  3. 本人40多岁大龄码农,国内已经没人要了,被优化后去日本工作,一人上班轻松养活三口之家!...
  4. Unity中通过Jint调用js库
  5. C语言中各运算符的优先级
  6. jupyter notebook使用心得
  7. java web电影售票系统
  8. 数学建模之Hermite插值法和三次样条插值法(附上详细的matlab代码)
  9. Vue.js入门 0x13 实战:知乎日报项目开发-文章详情页
  10. python库名_在python存储库名称和包名称中使用连字符/破折号 - python