从我一直在研究的项目之一,jQuery复制到剪贴板插件,利用了 零剪贴板 图书馆。
如果你是一个沉重的jQuery用户,它比原生的Zero Clipboard插件更容易使用。
将文本从HTML输入复制到剪贴板
function myFunction() { /* Get the text field */ var copyText = document.getElementById("myInput"); /* Select the text field */ copyText.select(); /* Copy the text inside the text field */ document.execCommand("Copy"); /* Alert the copied text */ alert("Copied the text: " + copyText.value); } <!-- The text field --> <input type="text" value="Hello Friend" id="myInput"> <!-- The button used to copy the text --> <button onclick="myFunction()">Copy text</button> 的 注意: 强> 该 document.execCommand() IE9及更早版本不支持该方法。
function myFunction() { /* Get the text field */ var copyText = document.getElementById("myInput"); /* Select the text field */ copyText.select(); /* Copy the text inside the text field */ document.execCommand("Copy"); /* Alert the copied text */ alert("Copied the text: " + copyText.value); }
<!-- The text field --> <input type="text" value="Hello Friend" id="myInput"> <!-- The button used to copy the text --> <button onclick="myFunction()">Copy text</button>
的 注意: 强> 该 document.execCommand() IE9及更早版本不支持该方法。
document.execCommand()
的 资源 强> : W3Schools - 将文本复制到剪贴板
我用过clipboard.js
我们可以在npm得到它
npm install clipboard --save
还有凉亭
bower install clipboard --save
用法&amp;例子是在 https://zenorocha.github.io/clipboard.js/
从网页读取和修改剪贴板会引起安全和隐私问题。但是,在Internet?Explorer中,可以这样做。我找到了这个 示例代码段 :
<script type="text/javascript"> function select_all(obj) { var text_val=eval(obj); text_val.focus(); text_val.select(); r = text_val.createTextRange(); if (!r.execCommand) return; // feature detection r.execCommand('copy'); } </script> <input value="http://www.sajithmr.com" onclick="select_all(this)" name="url" type="text" />
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上 。
的 注意: 强> 这已经被弃用了。迁移到 这里 。
从最近 Chrome 42+ 和 Firefox 41+ 现在支持了 的 document.execCommand( '复制') 强> 命令。因此,我使用组合的方式为跨浏览器复制到剪贴板功能创建了几个函数 蒂姆唐的老答案 和 Google Developer的答案 :
Chrome 42+
Firefox 41+
function selectElementContents(el) { // Copy textarea, pre, div, etc. if (document.body.createTextRange) { // IE var textRange = document.body.createTextRange(); textRange.moveToElementText(el); textRange.select(); textRange.execCommand("Copy"); } else if (window.getSelection && document.createRange) { // non-IE var range = document.createRange(); range.selectNodeContents(el); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Copy command was ' + msg); } catch (err) { console.log('Oops, unable to copy'); } } } // end function selectElementContents(el) function make_copy_button(el) { var copy_btn = document.createElement('input'); copy_btn.type = "button"; el.parentNode.insertBefore(copy_btn, el.nextSibling); copy_btn.onclick = function() { selectElementContents(el); }; if (document.queryCommandSupported("copy") || parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2]) >= 42) { // Copy works with IE 4+, Chrome 42+, Firefox 41+, Opera 29+ copy_btn.value = "Copy to Clipboard"; } else { // Select only for Safari and older Chrome, Firefox and Opera copy_btn.value = "Select All (then press CTRL+C to Copy)"; } } /* Note: document.queryCommandSupported("copy") should return "true" on browsers that support copy but there was a bug in Chrome versions 42 to 47 that makes it return "false". So in those versions of Chrome feature detection does not work! See https://code.google.com/p/chromium/issues/detail?id=476508 */ make_copy_button(document.getElementById("markup"));
<pre id="markup"> Text that can be copied or selected with cross browser support. </pre>
其他方法将纯文本复制到剪贴板。要复制HTML(即,您可以将结果粘贴到WSIWYG编辑器中),您可以执行以下操作 的 仅IE浏览器 强> 。这与其他方法根本不同,因为浏览器实际上可视地选择内容。
// create an editable DIV and append the HTML content you want copied var editableDiv = document.createElement("div"); with (editableDiv) { contentEditable = true; } editableDiv.appendChild(someContentElement); // select the editable content and copy it to the clipboard var r = document.body.createTextRange(); r.moveToElementText(editableDiv); r.select(); r.execCommand("Copy"); // deselect, so the browser doesn't leave the element visibly selected r.moveToElementText(someHiddenDiv); r.select();
这是@ Chase的答案的扩展,其优点是它可以用于IMAGE和TABLE元素,而不仅仅是IE9上的DIV。
if (document.createRange) { // IE9 and modern browsers var r = document.createRange(); r.setStartBefore(to_copy); r.setEndAfter(to_copy); r.selectNode(to_copy); var sel = window.getSelection(); sel.addRange(r); document.execCommand('Copy'); // does nothing on FF } else { // IE 8 and earlier. This stuff won't work on IE9. // (unless forced into a backward compatibility mode, // or selecting plain divs, not img or table). var r = document.body.createTextRange(); r.moveToElementText(to_copy); r.select() r.execCommand('Copy'); }
我最近写过一篇 技术博客文章 关于这个问题(我在Lucidchart工作,我们最近在剪贴板上进行了大修)。
将纯文本复制到剪贴板相对简单,假设您希望在系统复制事件期间执行此操作(用户按下 按Ctrl C 或使用浏览器的菜单)。
var isIe = (navigator.userAgent.toLowerCase().indexOf("msie") != -1 || navigator.userAgent.toLowerCase().indexOf("trident") != -1); document.addEventListener('copy', function(e) { var textToPutOnClipboard = "This is some text"; if (isIe) { window.clipboardData.setData('Text', textToPutOnClipboard); } else { e.clipboardData.setData('text/plain', textToPutOnClipboard); } e.preventDefault(); });
在系统复制事件期间不将文本放在剪贴板上要困难得多。看起来这些其他答案中的一些提到了通过Flash实现它的方法,这是唯一的跨浏览器方式(据我所知)。
除此之外,还有一些基于浏览器的选项。
这是IE中最简单的,您可以随时通过JavaScript访问clipboardData对象:
window.clipboardData
(但是,当您尝试在系统剪切,复制或粘贴事件之外执行此操作时,IE将提示用户授予Web应用程序剪贴板权限。)
在Chrome中,您可以创建一个Chrome扩展程序 剪贴板权限 (这就是我们为Lucidchart所做的事情)。然后,对于安装了扩展程序的用户,您只需要自己触发系统事件:
document.execCommand('copy');
它看起来像Firefox 一些选择 允许用户授予某些网站访问剪贴板的权限,但我没有亲自尝试过这些。
<!DOCTYPE html> <style> #t { width: 1px height: 1px border: none } #t:focus { outline: none } </style> <script> function copy(text) { var t = document.getElementById('t') t.innerHTML = text t.select() try { var successful = document.execCommand('copy') var msg = successful ? 'successfully' : 'unsuccessfully' console.log('text coppied ' + msg) } catch (err) { console.log('Unable to copy text') } t.innerHTML = '' } </script> <textarea id=t></textarea> <button onclick="copy('hello world')"> Click me </button>
在IE以外的浏览器中,您需要使用小型Flash对象来操作剪贴板,例如
我找到了以下解决方案:
按键向下处理程序创建“pre”标记。我们将内容设置为复制到此标记,然后对此标记进行选择并在处理程序中返回true。这会调用chrome的标准处理程序并复制所选文本。
如果需要,可以设置恢复先前选择的功能超时。我在Mootools上的实现:
function EnybyClipboard() { this.saveSelection = false; this.callback = false; this.pastedText = false; this.restoreSelection = function() { if (this.saveSelection) { window.getSelection().removeAllRanges(); for (var i = 0; i < this.saveSelection.length; i++) { window.getSelection().addRange(this.saveSelection[i]); } this.saveSelection = false; } }; this.copyText = function(text) { var div = $('special_copy'); if (!div) { div = new Element('pre', { 'id': 'special_copy', 'style': 'opacity: 0;position: absolute;top: -10000px;right: 0;' }); div.injectInside(document.body); } div.set('text', text); if (document.createRange) { var rng = document.createRange(); rng.selectNodeContents(div); this.saveSelection = []; var selection = window.getSelection(); for (var i = 0; i < selection.rangeCount; i++) { this.saveSelection[i] = selection.getRangeAt(i); } window.getSelection().removeAllRanges(); window.getSelection().addRange(rng); setTimeout(this.restoreSelection.bind(this), 100); } else return alert('Copy not work. :('); }; this.getPastedText = function() { if (!this.pastedText) alert('Nothing to paste. :('); return this.pastedText; }; this.pasteText = function(callback) { var div = $('special_paste'); if (!div) { div = new Element('textarea', { 'id': 'special_paste', 'style': 'opacity: 0;position: absolute;top: -10000px;right: 0;' }); div.injectInside(document.body); div.addEvent('keyup', function() { if (this.callback) { this.pastedText = $('special_paste').get('value'); this.callback.call(null, this.pastedText); this.callback = false; this.pastedText = false; setTimeout(this.restoreSelection.bind(this), 100); } }.bind(this)); } div.set('value', ''); if (document.createRange) { var rng = document.createRange(); rng.selectNodeContents(div); this.saveSelection = []; var selection = window.getSelection(); for (var i = 0; i < selection.rangeCount; i++) { this.saveSelection[i] = selection.getRangeAt(i); } window.getSelection().removeAllRanges(); window.getSelection().addRange(rng); div.focus(); this.callback = callback; } else return alert('Fail to paste. :('); }; }
用法:
enyby_clip = new EnybyClipboard(); //init enyby_clip.copyText('some_text'); // place this in CTRL+C handler and return true; enyby_clip.pasteText(function callback(pasted_text) { alert(pasted_text); }); // place this in CTRL+V handler and return true;
在粘贴时,它会创建textarea并以相同的方式工作。
PS可能是这个解决方案可用于创建完全跨浏览器的解决方案,无需闪存。它适用于FF和Chrome。
已经有很多答案,但我想添加一个(jQuery)。在任何浏览器上都可以像魅力一样工作,也可以在移动设备上工作(即提示有关安全性但是当你接受它时工作正常)。
function appCopyToClipBoard( sText ) { var oText = false, bResult = false; try { oText = document.createElement("textarea"); $(oText).addClass('clipboardCopier').val(sText).insertAfter('body').focus(); oText.select(); document.execCommand("Copy"); bResult = true; } catch(e) {} $(oText).remove(); return bResult; }
在你的代码中:
if( !appCopyToClipBoard( 'Hai there! This is copied to the clipboard.' )) { alert('Sorry, copy to clipboard failed.'); }
这是其他答案之间的一点组合。
var copyToClipboard = function(textToCopy){ $("body") .append($('<input type="text" name="fname" class="textToCopyInput"/>' ) .val(textToCopy)) .find(".textToCopyInput") .select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; alert('Text copied to clipboard!'); } catch (err) { window.prompt("To copy the text to clipboard: Ctrl+C, Enter", textToCopy); } $(".textToCopyInput").remove(); }
它使用jQuery,但它当然不需要。如果需要,您可以更改它。我刚才有jQuery供我使用。您还可以添加一些CSS以确保输入不显示。例如:
.textToCopyInput{opacity: 0; position: absolute;}
或者当然你也可以做一些内联样式
.append($('<input type="text" name="fname" style="opacity: 0; position: absolute;" class="textToCopyInput"/>' )
要将选定的文本(“要复制的文本”)复制到剪贴板,请创建一个Bookmarklet(执行Javsacript的浏览器书签)并执行它(单击它)。 它将创建一个临时文本区域。
Github的代码:
https://gist.github.com/stefanmaric/2abf96c740191cda3bc7a8b0fc905a7d
(function (text) { var node = document.createElement('textarea'); var selection = document.getSelection(); node.textContent = text; document.body.appendChild(node); selection.removeAllRanges(); node.select(); document.execCommand('copy'); selection.removeAllRanges(); document.body.removeChild(node); })('Text To Copy');
自动复制到剪贴板可能很危险,因此大多数浏览器(IE除外)都非常困难。就个人而言,我使用以下简单的技巧:
function copyToClipboard(text) { window.prompt("Copy to clipboard: Ctrl+C, Enter", text); }
将向用户显示提示框,其中已选择要复制的文本。现在它足以按下了 按Ctrl + C 和 输入 (关闭盒子) - 瞧!
现在剪贴板复制操作是SAFE,因为用户手动完成(但是以非常简单的方式)。当然,适用于所有浏览器。
<button id="demo" onclick="copyToClipboard(document.getElementById('demo').innerHTML)">This is what I want to copy</button> <script> function copyToClipboard(text) { window.prompt("Copy to clipboard: Ctrl+C, Enter", text); } </script>