San*_*ira 3131 javascript clipboard copy-paste
将文本复制到剪贴板的最佳方法是什么?(多浏览器)
我试过了:
function copyToClipboard(text) {
if (window.clipboardData) { // Internet Explorer
window.clipboardData.setData("Text", text);
} else {
unsafeWindow.netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
const clipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
clipboardHelper.copyString(text);
}
}
Run Code Online (Sandbox Code Playgroud)
但在Internet Explorer中,它会出现语法错误.在Firefox中,它说unsafeWindow is not defined.
没有闪存的好技巧:Trello如何访问用户的剪贴板?
Dea*_*lor 2029
有三种主要的浏览器API可用于复制到剪贴板:
[navigator.clipboard.writeText]
document.execCommand('copy')
在控制台中测试代码时,不要指望与剪贴板相关的命令可以正常工作.通常,页面必须是活动的(Async Clipboard API)或需要用户交互(例如用户单击)以允许(document.execCommand('copy'))访问剪贴板,请参阅下面的更多详细信息.
由于浏览器支持新的Async Clipboard API,您可能希望回退到该document.execCommand('copy')方法以获得良好的浏览器覆盖率.
这是一个简单的例子:
function fallbackCopyTextToClipboard(text) {
var textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.position="fixed"; //avoid scrolling to bottom
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Fallback: Copying text command was ' + msg);
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
}
document.body.removeChild(textArea);
}
function copyTextToClipboard(text) {
if (!navigator.clipboard) {
fallbackCopyTextToClipboard(text);
return;
}
navigator.clipboard.writeText(text).then(function() {
console.log('Async: Copying to clipboard was successful!');
}, function(err) {
console.error('Async: Could not copy text: ', err);
});
}
var copyBobBtn = document.querySelector('.js-copy-bob-btn'),
copyJaneBtn = document.querySelector('.js-copy-jane-btn');
copyBobBtn.addEventListener('click', function(event) {
copyTextToClipboard('Bob');
});
copyJaneBtn.addEventListener('click', function(event) {
copyTextToClipboard('Jane');
});Run Code Online (Sandbox Code Playgroud)
<div style="display:inline-block; vertical-align:top;">
<button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />
<button class="js-copy-jane-btn">Set clipboard to JANE</button>
</div>
<div style="display:inline-block;">
<textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:
</textarea>
</div>Run Code Online (Sandbox Code Playgroud)
请注意,此代码段在Stack Overflow的嵌入式预览中无法正常运行,您可以在此处尝试:https://codepen.io/DeanMarkTaylor/pen/RMRaJX?edit = 1011
请注意,可以通过Chrome 66中的权限API"请求权限"并测试对剪贴板的访问权限.
var text = "Example text to appear on clipboard";
navigator.clipboard.writeText(text).then(function() {
console.log('Async: Copying to clipboard was successful!');
}, function(err) {
console.error('Async: Could not copy text: ', err);
});
Run Code Online (Sandbox Code Playgroud)
本文的其余部分将介绍document.execCommand('copy')API 的细微差别和细节.
JavaScript document.execCommand('copy')支持已经增长,请参阅下面的链接以获取浏览器更新:
var copyTextareaBtn = document.querySelector('.js-textareacopybtn');
copyTextareaBtn.addEventListener('click', function(event) {
var copyTextarea = document.querySelector('.js-copytextarea');
copyTextarea.focus();
copyTextarea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
});Run Code Online (Sandbox Code Playgroud)
<p>
<button class="js-textareacopybtn" style="vertical-align:top;">Copy Textarea</button>
<textarea class="js-copytextarea">Hello I'm some text</textarea>
</p>Run Code Online (Sandbox Code Playgroud)
如果有一个以上简单例子的伟大工程,textarea或input在屏幕上可见的元素.
在某些情况下,您可能希望将文本复制到剪贴板而不显示input/ textarea元素.这是解决此问题的一种方法示例(基本上是插入元素,复制到剪贴板,删除元素):
使用Google Chrome 44,Firefox 42.0a1和Internet Explorer 11.0.8600.17814进行测试.
function copyTextToClipboard(text) {
var textArea = document.createElement("textarea");
//
// *** This styling is an extra step which is likely not required. ***
//
// Why is it here? To ensure:
// 1. the element is able to have focus and selection.
// 2. if element was to flash render it has minimal visual impact.
// 3. less flakyness with selection and copying which **might** occur if
// the textarea element is not visible.
//
// The likelihood is the element won't even render, not even a
// flash, so some of these are just precautions. However in
// Internet Explorer the element is visible whilst the popup
// box asking the user for permission for the web page to
// copy to the clipboard.
//
// Place in top-left corner of screen regardless of scroll position.
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
// Ensure it has a small width and height. Setting to 1px / 1em
// doesn't work as this gives a negative w/h on some browsers.
textArea.style.width = '2em';
textArea.style.height = '2em';
// We don't need padding, reducing the size if it does flash render.
textArea.style.padding = 0;
// Clean up any borders.
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
// Avoid flash of white box if rendered for any reason.
textArea.style.background = 'transparent';
textArea.value = text;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
document.body.removeChild(textArea);
}
var copyBobBtn = document.querySelector('.js-copy-bob-btn'),
copyJaneBtn = document.querySelector('.js-copy-jane-btn');
copyBobBtn.addEventListener('click', function(event) {
copyTextToClipboard('Bob');
});
copyJaneBtn.addEventListener('click', function(event) {
copyTextToClipboard('Jane');
});Run Code Online (Sandbox Code Playgroud)
<div style="display:inline-block; vertical-align:top;">
<button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />
<button class="js-copy-jane-btn">Set clipboard to JANE</button>
</div>
<div style="display:inline-block;">
<textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:
</textarea>
</div>Run Code Online (Sandbox Code Playgroud)
所有document.execCommand('copy')调用必须作为用户操作的直接结果发生,例如单击事件处理程序.这是一种措施,可以防止在用户剪贴板不期望时弄乱用户的剪贴板.
有关详细信息,请参阅此处的Google Developers帖子.
注意完整的剪贴板API草案规范可以在这里找到:https: //w3c.github.io/clipboard-apis/
document.queryCommandSupported('copy')true如果命令"由浏览器支持",则应该返回.document.queryCommandEnabled('copy')返回true如果document.execCommand('copy')会成功,如果现在叫.检查以确保从用户启动的线程调用该命令并满足其他要求.但是,作为浏览器兼容性问题的示例,只有从用户启动的线程调用该命令时,才会true从2015年4月到10月的Google Chrome返回document.queryCommandSupported('copy').
请注意以下兼容性细节
虽然通过用户单击调用document.execCommand('copy')包含在try/ catch块中的简单调用将获得最大的兼容性,但以下内容有一些附带条件:
任何调用document.execCommand,document.queryCommandSupported或document.queryCommandEnabled应该包含在try/ catchblock中.
不同的浏览器实现和浏览器版本在调用而不是返回时会抛出不同类型的异常false.
不同的浏览器实现仍在不断变化,剪贴板API仍处于草案状态,因此请记住进行测试.
小智 1237
自动复制到剪贴板可能很危险,因此大多数浏览器(IE除外)都非常困难.就个人而言,我使用以下简单的技巧:
function copyToClipboard(text) {
window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}
Run Code Online (Sandbox Code Playgroud)
将向用户显示提示框,其中已选择要复制的文本.现在它足以按Ctrl+ C和Enter(关闭框) - 瞧!
现在剪贴板复制操作是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>Run Code Online (Sandbox Code Playgroud)
Gre*_*owe 269
以下方法适用于Chrome,Firefox,Internet Explorer和Edge以及最新版本的Safari(在2016年10月发布的版本10中添加了复制支持).
注意:您将看不到textarea,因为它是在Javascript代码的同一个同步调用中添加和删除的.
如果您自己实现这一点,需要注意的一些事项:
以下功能应尽可能干净地处理以下所有问题.如果您发现任何问题或有任何改进建议,请发表评论.
// Copies a string to the clipboard. Must be called from within an
// event handler such as click. May return false if it failed, but
// this is not always possible. Browser support for Chrome 43+,
// Firefox 42+, Safari 10+, Edge and Internet Explorer 10+.
// Internet Explorer: The clipboard feature may be disabled by
// an administrator. By default a prompt is shown the first
// time the clipboard is used (per session).
function copyToClipboard(text) {
if (window.clipboardData && window.clipboardData.setData) {
// Internet Explorer-specific code path to prevent textarea being shown while dialog is visible.
return clipboardData.setData("Text", text);
}
else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
var textarea = document.createElement("textarea");
textarea.textContent = text;
textarea.style.position = "fixed"; // Prevent scrolling to bottom of page in Microsoft Edge.
document.body.appendChild(textarea);
textarea.select();
try {
return document.execCommand("copy"); // Security exception may be thrown by some browsers.
}
catch (ex) {
console.warn("Copy to clipboard failed.", ex);
return false;
}
finally {
document.body.removeChild(textarea);
}
}
}
Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/fx6a6n6x/
Bre*_*lle 93
如果你想要一个非常简单的解决方案(整合时间不到5分钟)并且开箱即用,那么Clippy是一些更复杂的解决方案的不错选择.
它是由GitHub的联合创始人撰写的.示例Flash嵌入代码如下:
<object
classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
width="110"
height="14"
id="clippy">
<param name="movie" value="/flash/clippy.swf"/>
<param name="allowScriptAccess" value="always"/>
<param name="quality" value="high"/>
<param name="scale" value="noscale"/>
<param NAME="FlashVars" value="text=#{text}"/>
<param name="bgcolor" value="#{bgcolor}"/>
<embed
src="/flash/clippy.swf"
width="110"
height="14"
name="clippy"
quality="high"
allowScriptAccess="always"
type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer"
FlashVars="text=#{text}"
bgcolor="#{bgcolor}"/>
</object>
Run Code Online (Sandbox Code Playgroud)
请记住#{text}用您需要复制的文本和#{bgcolor}颜色替换.
ban*_*ndi 84
从网页读取和修改剪贴板会引起安全和隐私问题.但是,在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" />Run Code Online (Sandbox Code Playgroud)
Mat*_*agg 72
我喜欢这个:
<input onclick="this.select();" type='text' value='copy me' />
Run Code Online (Sandbox Code Playgroud)
如果用户不知道如何在他们的操作系统中复制文本,那么他们很可能也不知道如何粘贴。所以只需自动选择它,剩下的交给用户。
Ric*_*rtz 69
我最近写了一篇关于这个问题的技术博客文章(我在Lucidchart工作,我们最近在剪贴板上进行了大修).
将纯文本复制到剪贴板相对简单,假设您希望在系统复制事件期间(用户按下CtrlC或使用浏览器菜单)执行此操作.
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();
});
Run Code Online (Sandbox Code Playgroud)
在系统复制事件期间不将文本放在剪贴板上要困难得多.看起来这些其他答案中的一些提到了通过Flash实现它的方法,这是唯一的跨浏览器方式(据我所知).
除此之外,还有一些基于浏览器的选项.
这是IE中最简单的,您可以随时通过JavaScript访问clipboardData对象:
window.clipboardData
Run Code Online (Sandbox Code Playgroud)
(但是,当您尝试在系统剪切,复制或粘贴事件之外执行此操作时,IE将提示用户授予Web应用程序剪贴板权限.)
在Chrome中,您可以创建Chrome扩展程序,为您提供剪贴板权限(这就是我们为Lucidchart所做的工作).然后,对于安装了扩展程序的用户,您只需要自己触发系统事件:
document.execCommand('copy');
Run Code Online (Sandbox Code Playgroud)
看起来Firefox有一些选项允许用户授予某些站点访问剪贴板的权限,但我没有亲自尝试过这些.
nik*_*san 57
这是我对那一个的看法..
function copy(text) {
var input = document.createElement('input');
input.setAttribute('value', text);
document.body.appendChild(input);
input.select();
var result = document.execCommand('copy');
document.body.removeChild(input);
return result;
}
Run Code Online (Sandbox Code Playgroud)
a c*_*der 48
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>
Run Code Online (Sandbox Code Playgroud)
clipboard.js也在GitHub上.
注意:现在已弃用.迁移到这里.
小智 40
JavaScript/TypeScript 中最好、最简单的方法是使用此命令
navigator.clipboard.writeText(textExample);
Run Code Online (Sandbox Code Playgroud)
只需在textExample中传递您想要复制到剪贴板的值
Jus*_*tin 35
ZeroClipboard是我发现的最佳跨浏览器解决方案:
<div id="copy" data-clipboard-text="Copy Me!">Click to copy</div>
<script src="ZeroClipboard.js"></script>
<script>
var clip = new ZeroClipboard( document.getElementById('copy') );
</script>
Run Code Online (Sandbox Code Playgroud)
如果您需要iOS的非Flash支持,您只需添加一个后备:
clip.on( 'noflash', function ( client, args ) {
$("#copy").click(function(){
var txt = $(this).attr('data-clipboard-text');
prompt ("Copy link, then click OK.", txt);
});
});
Run Code Online (Sandbox Code Playgroud)
https://github.com/zeroclipboard/ZeroClipboard
小智 26
从我一直在研究的项目之一,jQuery复制到剪贴板插件,利用Zero Clipboard库.
如果你是一个沉重的jQuery用户,它比原生的Zero Clipboard插件更容易使用.
小智 25
$("td").click(function (e) {
var clickedCell = $(e.target).closest("td");
navigator.clipboard.writeText(clickedCell.text());
alert(clickedCell.text());
});Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>First<td>
</tr>
<tr>
<td>Second<td>
</tr>
<tr>
<td>Third<td>
</tr>
<tr>
<td>Fourth<td>
</tr>
</table>Run Code Online (Sandbox Code Playgroud)
我已经阅读了所有答案,截至 2020 年 6 月 1 日,当我终于找到文档时,我一直在努力解决这个问题:
$("td").click(function (e) {
var clickedCell = $(e.target).closest("td");
navigator.clipboard.writeText(clickedCell.text());
});
Run Code Online (Sandbox Code Playgroud)
它会将单击的单元格文本写入浏览器剪贴板。
您可以根据需要更改选择器“td”,您可以添加用于调试和/或警报功能的 console.log。
这是文档:https : //developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText
Kho*_*Phi 24
Geesh,不知道为什么没有人指出这个.
在2018年,伙计们,这是你如何去做的:
async copySomething(text?) {
try {
const toCopy = text || location.href;
await navigator.clipboard.writeText(toCopy);
console.log('Text or Page URL copied');
}
catch (err) {
console.error('Failed to copy: ', err);
}
}
Run Code Online (Sandbox Code Playgroud)
在我的Angular 6+代码中使用,如下所示:
<button mat-menu-item (click)="copySomething()">
<span>Copy link</span>
</button>
Run Code Online (Sandbox Code Playgroud)
如果我传入一个字符串,它会复制它.如果没有,请复制页面的URL.
也可以做更多体操到剪贴板的东西.在这里查看更多信息:
https://developers.google.com/web/updates/2018/03/clipboardapi
Jos*_*nce 24
我不愿意对此添加另一个答案,但为了帮助像我这样的菜鸟,而且因为这是我会的最佳谷歌结果。
到 2022 年,要将文本复制到剪贴板,只需一行即可。
navigator.clipboard.writeText(textToCopy);
Run Code Online (Sandbox Code Playgroud)
这将返回一个 Promise,如果复制则解决该 Promise,如果失败则拒绝。
完整的工作函数是这样的:
async function copyTextToClipboard(textToCopy) {
try {
await navigator.clipboard.writeText(textToCopy);
console.log('copied to clipboard')
} catch (error) {
console.log('failed to copy to clipboard. error=' + error);
}
}
Run Code Online (Sandbox Code Playgroud)
警告!如果您在测试时打开了 Chrome 开发工具,它将失败,因为浏览器要启用剪贴板,它需要您将窗口置于焦点中。这是为了防止随机网站在您不想要的情况下更改您的剪贴板。开发工具抢走了这个焦点,因此靠近开发工具,您的测试就会起作用。
如果您想将其他内容(图像等)复制到剪贴板,请查看这些文档。
https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API
这在浏览器中得到了很好的支持,您可以使用它。如果您担心 Firefox,请使用权限查询来显示或隐藏按钮(如果浏览器支持)。https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query
Eny*_*yby 22
我找到了以下解决方案:
按键向下处理程序创建"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. :(');
};
}
Run Code Online (Sandbox Code Playgroud)
用法:
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;
Run Code Online (Sandbox Code Playgroud)
在粘贴时,它会创建textarea并以相同的方式工作.
PS可能是这个解决方案可用于创建完全跨浏览器的解决方案,无需闪存.它适用于FF和Chrome.
Jef*_*ker 22
从最近起__CODE__,__CODE__现在支持document.execCommand('copy')命令.所以我使用Tim Down的旧答案和Google Developer的答案组合创建了一些跨浏览器复制到剪贴板功能的功能:
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-Internet Explorer
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 Internet Explorer 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"));Run Code Online (Sandbox Code Playgroud)
<pre id="markup">
Text that can be copied or selected with cross browser support.
</pre>Run Code Online (Sandbox Code Playgroud)
Pet*_*der 22
我非常成功地使用它(没有 jquery或任何其他框架).
function copyToClp(txt){
txt = document.createTextNode(txt);
var m = document;
var w = window;
var b = m.body;
b.appendChild(txt);
if (b.createTextRange) {
var d = b.createTextRange();
d.moveToElementText(txt);
d.select();
m.execCommand('copy');
}
else {
var d = m.createRange();
var g = w.getSelection;
d.selectNodeContents(txt);
g().removeAllRanges();
g().addRange(d);
m.execCommand('copy');
g().removeAllRanges();
}
txt.remove();
}
Run Code Online (Sandbox Code Playgroud)
警告
标签转换为空格(至少在chrome中).
Cha*_*ert 21
其他方法将纯文本复制到剪贴板.要复制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();
Run Code Online (Sandbox Code Playgroud)
Dom*_*nic 20
我把我认为最好的一个放在一起.
这里是:
const copyToClipboard = (function initClipboardText() {
const textarea = document.createElement('textarea');
// Move it off screen.
textarea.style.cssText = 'position: absolute; left: -99999em';
// Set to readonly to prevent mobile devices opening a keyboard when
// text is .select()'ed.
textarea.setAttribute('readonly', true);
document.body.appendChild(textarea);
return function setClipboardText(text) {
textarea.value = text;
// Check if there is any content selected previously.
const selected = document.getSelection().rangeCount > 0 ?
document.getSelection().getRangeAt(0) : false;
// iOS Safari blocks programmtic execCommand copying normally, without this hack.
// https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios
if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
const editable = textarea.contentEditable;
textarea.contentEditable = true;
const range = document.createRange();
range.selectNodeContents(textarea);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
textarea.setSelectionRange(0, 999999);
textarea.contentEditable = editable;
}
else {
textarea.select();
}
try {
const result = document.execCommand('copy');
// Restore previous selection.
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
return result;
}
catch (err) {
console.error(err);
return false;
}
};
})();
Run Code Online (Sandbox Code Playgroud)
NVR*_*VRM 17
使用最新的Clipboard API和用户交互,这可以立即生效:
copy.addEventListener("pointerdown", () => navigator.clipboard.writeText("Hello World!"))Run Code Online (Sandbox Code Playgroud)
<button id="copy">Copy Hello World!</button>Run Code Online (Sandbox Code Playgroud)
HO *_*Pin 16
此代码在 2021 年 5 月进行了测试。在 Chrome、IE、Edge 上工作。下面的“消息”参数是您要复制的字符串值。
<script type="text/javascript">
function copyToClipboard(message) {
var textArea = document.createElement("textarea");
textArea.value = message;
textArea.style.opacity = "0";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
alert('Copying text command was ' + msg);
} catch (err) {
alert('Unable to copy value , error : ' + err.message);
}
document.body.removeChild(textArea);
}
</script>
Run Code Online (Sandbox Code Playgroud)
mat*_*ins 13
从Flash 10开始,如果操作源自用户与Flash对象的交互,则只能复制到剪贴板.(阅读Adobe Flash 10公告中的相关部分)
解决方案是在Copy按钮上方过度使用flash对象,或者启动副本的任何元素.零剪贴板目前是具有此实现的最佳库.有经验的Flash开发人员可能只想创建自己的库.
小智 13
<!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>Run Code Online (Sandbox Code Playgroud)
小智 13
复制文本字段内文本的最佳方法。使用navigator.clipboard.writeText。
<input type="text" value="Hello World" id="myId">
<button onclick="myFunction()" >Copy text</button>
<script>
function myFunction() {
var copyText = document.getElementById("myId");
copyText.select();
copyText.setSelectionRange(0, 99999);
navigator.clipboard.writeText(copyText.value);
}
</script>
Run Code Online (Sandbox Code Playgroud)
Vas*_*las 12
我找到了以下解决方案:
我将文本隐藏在输入中.因为setSelectionRange不能对隐藏的输入起作用,我暂时将类型更改为文本,复制文本然后再次隐藏它.如果要从元素复制文本,可以将其传递给函数并将其内容保存在目标变量中.
jQuery('#copy').on('click', function () {
copyToClipboard();
});
function copyToClipboard() {
var target = jQuery('#hidden_text');
// Make it visible, so can be focused
target.attr('type', 'text');
target.focus();
// Select all the text
target[0].setSelectionRange(0, target.val().length);
// Copy the selection
var succeed;
try {
succeed = document.execCommand("copy");
}
catch (e) {
succeed = false;
}
// Hide input again
target.attr('type', 'hidden');
return succeed;
}
Run Code Online (Sandbox Code Playgroud)
Cod*_*eat 11
已经有很多答案,但我想添加一个(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;
}
Run Code Online (Sandbox Code Playgroud)
在你的代码中:
if (!appCopyToClipBoard('Hai there! This is copied to the clipboard.'))
{
alert('Sorry, copy to clipboard failed.');
}
Run Code Online (Sandbox Code Playgroud)
小智 10
将文本从HTML输入复制到剪贴板
Run Code Online (Sandbox Code Playgroud)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); }Run Code Online (Sandbox Code Playgroud)<!-- The text field --> <input type="text" value="Hello Friend" id="myInput"> <!-- The button used to copy the text --> <button onclick="myFunction()">Copy text</button>注意: IE9及更早版本不支持该
document.execCommand()方法.
小智 8
我在构建自定义网格编辑时遇到了同样的问题(例如Excel)和与Excel的兼容性.我不得不支持选择多个单元格,复制和粘贴.
解决方案:创建一个textarea,您将插入数据供用户复制(对我来说,当用户选择单元格时),设置焦点(例如,当用户按下时Ctrl)并选择整个文本.
因此,当用户点击Ctrl+ C他/她获得他/她选择的复制的单元格时.测试后只需将textarea调整为一个像素(我没有测试它是否将在显示器上工作:无).它适用于所有浏览器,对用户来说是透明的.
粘贴 - 你可以这样做(你的目标不同) - 继续关注textarea并使用onpaste捕捉粘贴事件(在我的项目中,我使用单元格中的textareas进行编辑).
我不能粘贴一个例子(商业项目),但你明白了.
这是其他答案之间的一点组合.
var copyToClipboard = function(textToCopy){
$("body")
.append($('<textarea 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();
}
Run Code Online (Sandbox Code Playgroud)
它使用jQuery,但它当然不需要.如果需要,您可以更改它.我刚才有jQuery供我使用.您还可以添加一些CSS以确保输入不显示.例如:
.textToCopyInput{opacity: 0; position: absolute;}
Run Code Online (Sandbox Code Playgroud)
或者当然你也可以做一些内联样式
.append($('<textarea name="fname" style="opacity: 0; position: absolute;" class="textToCopyInput"/>' )
Run Code Online (Sandbox Code Playgroud)
小智 8
function copytoclipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val('0' + element).select();
document.execCommand("copy");
$temp.remove();
}
Run Code Online (Sandbox Code Playgroud)
这是@ 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');
}
Run Code Online (Sandbox Code Playgroud)
我用过clipboard.js
我们可以在npm得到它
npm install clipboard --save
Run Code Online (Sandbox Code Playgroud)
还有凉亭
bower install clipboard --save
Run Code Online (Sandbox Code Playgroud)
用法和示例位于https://zenorocha.github.io/clipboard.js/
据我所知,这只适用于 Internet Explorer。
另请参阅Dynamic Tools - JavaScript Copy To Clipboard,但它要求用户首先更改配置,即使如此,它似乎也不起作用。
看起来您从Greasemonkey\JavaScript Copy to Clipboard 按钮或此代码段的原始来源中获取了代码...
此代码用于 Greasemonkey,因此是 unsafeWindow。而且我猜 Internet Explorer 中的语法错误来自const特定于 Firefox的关键字(将其替换为var)。
我似乎误解了这个问题,但作为参考,你可以提取一系列DOM(不是剪贴板;与所有现代浏览器兼容),并将它与oncopy和onpaste以及onbeforepaste事件结合起来以获得剪贴板行为.这是实现此目的的代码:
function clipBoard(sCommand) {
var oRange=contentDocument.createRange();
oRange.setStart(startNode, startOffset);
oRange.setEnd(endNode, endOffset);
/* This is where the actual selection happens.
in the above, startNode and endNode are dom nodes defining the beginning
and end of the "selection" respectively. startOffset and endOffset are
constants that are defined as follows:
END_TO_END: 2
END_TO_START: 3
NODE_AFTER: 1
NODE_BEFORE: 0
NODE_BEFORE_AND_AFTER: 2
NODE_INSIDE: 3
START_TO_END: 1
START_TO_START: 0
and would be used like oRange.START_TO_END */
switch(sCommand) {
case "cut":
this.oFragment=oRange.extractContents();
oRange.collapse();
break;
case "copy":
this.oFragment=oRange.cloneContents();
break;
case "paste":
oRange.deleteContents();
var cloneFragment=this.oFragment.cloneNode(true)
oRange.insertNode(cloneFragment);
oRange.collapse();
break;
}
}
Run Code Online (Sandbox Code Playgroud)
我的错.这仅适用于IE.
这是另一种复制文本的方法:
<p>
<a onclick="window.clipboardData.setData('text', document.getElementById('Test').innerText);">Copy</a>
</p>
Run Code Online (Sandbox Code Playgroud)
小智 5
在查找了互联网上的各种方法之后,这是我唯一能够工作的东西.这是一个混乱的话题.世界各地发布了大量解决方案,其中大部分都无效.这对我有用:
注意:此代码仅在作为"onClick"方法的直接同步代码执行时才有效.如果您调用对ajax的异步响应或以任何其他异步方式调用它将无法正常工作
copyToClipboard(text) {
var copyText = document.createElement("input");
copyText.type = "text";
document.body.appendChild(copyText);
copyText.style = "display: inline; width: 1px;";
copyText.value = text;
copyText.focus();
document.execCommand("SelectAll");
document.execCommand("Copy");
copyText.remove();
}
Run Code Online (Sandbox Code Playgroud)
我确实意识到这个代码会在屏幕上显示一个1px宽的组件,显示毫秒,但决定不要担心,这是其他人可以解决的问题,如果真的有问题.
要将选定的文本("要复制的文本")复制到剪贴板,请创建一个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');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1702317 次 |
| 最近记录: |