Async Clipboard API方法
HTML5新增的方法,无需引入第三方插件,直接就可以复制内容。低版本的浏览器可能会不兼容。
const promise = navigator.clipboard.writeText(newClipText);
方法的返回值是个 Promise。并且使用此方法时,页面必须处于 focus 状态,否则会报错。
覆写copy 事件方法
// Overwrite what is being copied to the clipboard.
document.addEventListener('copy', function (e) {
// e.clipboardData is initially empty, but we can set it to the
// data that we want copied onto the clipboard.
e.clipboardData.setData('text/plain', '西炒蛋');
// This is necessary to prevent the current document selection from
// being written to the clipboard.
e.preventDefault();
});Document.execCommandAPI方法
<p id="content">123456</p> <button id="copyButton">复制</button>
复制div元素内容
const copyButton = document.getElementById('copyButton');
const content = document.getElementById('content');
copyButton.addEventListener('click', function () {
const selection = window.getSelection();
const range = document.createRange();
// 缓存用户选中的内容
const currentRange =
selection.rangeCount === 0 ? null : selection.getRangeAt(0);
// 设置文档片段
range.selectNodeContents(content);
// 清空选中内容
selection.removeAllRanges();
// 将文档片段设置为选中内容
selection.addRange(range);
try {
// 复制到剪贴板
document.execCommand('copy');
} catch (err) {
// 提示复制失败
} finally {
selection.removeAllRanges();
if (currentRange) {
// 还原用户选中内容
selection.addRange(currentRange);
}
}
});复制input元素内容
const copyButton = document.getElementById('copyButton');
const inputEl = document.getElementById('input');
copyButton.addEventListener('click', function () {
const selection = window.getSelection();
const currentRange =
selection.rangeCount === 0 ? null : selection.getRangeAt(0);
// 选中 input 内容
inputEl.select();
// 复制到剪贴板
try {
document.execCommand('copy');
} catch (err) {
// 提示复制失败
// 。。。
} finally {
selection.removeAllRanges();
if (currentRange) {
// 还原用户选中内容
selection.addRange(currentRange);
}
}
});