.jpg)
如何将文本复制到剪贴板(多浏览器)?
相关: Trello 如何访问用户的剪贴板?

网友回答:
自动复制到剪贴板可能很危险,因此大多数浏览器(Internet Explorer 除外)都使其非常困难。就个人而言,我使用以下简单的技巧:
function copyToClipboard(text) {
window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}
用户将看到提示框,其中已选择要复制的文本。现在按 + 和(关闭框)就足够了 — 瞧!CtrlCEnter
现在剪贴板复制操作是安全的,因为用户手动完成(但以一种非常简单的方式)。当然,它适用于所有浏览器。
<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>

网友回答:
有三个主要的浏览器 API 可用于复制到剪贴板:
[navigator.clipboard.writeText]
document.execCommand('copy') (已弃用)?
不要指望在控制台中测试代码时与剪贴板相关的命令会起作用。通常,页面需要处于活动状态(异步剪贴板 API)或需要用户交互(例如用户单击)以允许 () 访问剪贴板,请参阅下文以了解更多详细信息。document.execCommand('copy')
请注意,由于这篇文章最初是写的,因此弃用跨源 IFRAME 和其他 IFRAME “沙盒”中的权限会阻止嵌入式演示“运行代码片段”按钮和“codepen.io 示例”在某些浏览器(包括 Chrome 和 Microsoft Edge)中工作。
若要开发 创建自己的网页,请通过 HTTPS 连接提供该页面以进行测试和开发。
这是一个测试/演示页面,演示了代码的工作原理:
https://deanmarktaylor.github.io/clipboard-test/
由于浏览器对新异步剪贴板 API 的支持级别,您可能希望回退到该方法以获得良好的浏览器覆盖率。document.execCommand('copy')
这里有一个简单的例子(可能不适用于嵌入在这个网站中,请阅读上面的“重要”注释):
function fallbackCopyTextToClipboard(text) {
var textArea = document.createElement("textarea");
textArea.value = text;
// Avoid scrolling to bottom
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";
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');
});
<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>
(codepen.io 示例可能不起作用,请阅读上面的“重要”注释)
请注意,此代码段在Stack Overflow的嵌入式预览中效果不佳,您可以在此处尝试:https://codepen.io/DeanMarkTaylor/pen/RMRaJX?editors=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);
});
本文的其余部分将介绍 API 的细微差别和细节。document.execCommand('copy')
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');
}
});
<p>
<button class="js-textareacopybtn" style="vertical-align:top;">Copy Textarea</button>
<textarea class="js-copytextarea">Hello I'm some text</textarea>
</p>
如果屏幕上有一个 or 元素可见,上面的简单示例效果很好。textareainput
在某些情况下,您可能希望将文本复制到剪贴板而不显示 / 元素。这是解决此问题的方法的一个例子(基本上插入一个元素,复制到剪贴板,删除元素):inputtextarea
使用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 the 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 the 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 the 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');
});
<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>
所有调用都必须作为用户操作的直接结果进行,例如单击事件处理程序。这是一种防止在用户不期望时弄乱剪贴板的措施。document.execCommand('copy')
有关更多信息,请参阅此处的 Google 开发者帖子。
请注意,完整的剪贴板 API 草案规范可在此处找到:
https://w3c.github.io/clipboard-apis/
document.queryCommandSupported('copy')如果命令“浏览器支持”,则应返回。truedocument.queryCommandEnabled('copy')truedocument.execCommand('copy')但是,作为浏览器兼容性问题的示例,2015 年 <> 月至 ~<> 月的 Google Chrome 仅在从用户启动的线程调用命令时才返回。truedocument.queryCommandSupported('copy')
请注意下面的兼容性详细信息。
虽然由于用户点击而调用的包裹在 / 块中的简单调用将为您带来最大的兼容性使用,但以下内容有一些附带条件:document.execCommand('copy')trycatch
任何对 或 的调用都应包装在 / 块中。document.execCommanddocument.queryCommandSupporteddocument.queryCommandEnabledtrycatch
不同的浏览器实现和浏览器版本在调用而不是返回时会引发不同类型的异常。false
不同的浏览器实现仍在不断变化,剪贴板 API 仍在草稿中,因此请记住进行测试。

网友回答:
以下方法适用于Chrome,Firefox,Internet Explorer和Edge以及最新版本的Safari(复制支持在10年2016月发布的版本<>中添加)。
注意:您不会看到文本区域,因为它是在 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 window.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 prompt("Copy to clipboard: Ctrl+C, Enter", text);
}
finally {
document.body.removeChild(textarea);
}
}
}
模板简介:该模板名称为【如何将文本复制到剪贴板(多浏览器)?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【JavaScript】栏目查找您需要的精美模板。