js 实现复制
使用 document.execCommand
在较旧的浏览器中,可以通过 document.execCommand 方法实现复制功能。创建一个临时的 textarea 或 input 元素,将需要复制的文本赋值给它,选中内容后执行复制命令。

function copyText(text) {
const textarea = document.createElement('textarea');
textarea.value = text;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
}
使用 Clipboard API
现代浏览器推荐使用 Clipboard API 的 writeText 方法实现复制功能。该方法返回一个 Promise,可以处理复制成功或失败的情况。

function copyText(text) {
navigator.clipboard.writeText(text)
.then(() => {
console.log('复制成功');
})
.catch(err => {
console.error('复制失败:', err);
});
}
结合兼容性检查
为了兼容新旧浏览器,可以结合两种方法,先检查 Clipboard API 是否可用,不可用时回退到 document.execCommand。
function copyText(text) {
if (navigator.clipboard) {
navigator.clipboard.writeText(text)
.then(() => {
console.log('复制成功');
})
.catch(err => {
console.error('复制失败,尝试回退方法:', err);
fallbackCopyText(text);
});
} else {
fallbackCopyText(text);
}
}
function fallbackCopyText(text) {
const textarea = document.createElement('textarea');
textarea.value = text;
document.body.appendChild(textarea);
textarea.select();
try {
document.execCommand('copy');
console.log('复制成功');
} catch (err) {
console.error('复制失败:', err);
}
document.body.removeChild(textarea);
}
复制特定元素内容
如果需要复制页面中某个元素的内容(如 div 或 pre),可以通过获取元素的 textContent 或 innerText 实现。
function copyElementContent(elementId) {
const element = document.getElementById(elementId);
if (element) {
copyText(element.textContent || element.innerText);
}
}
注意事项
- 使用 Clipboard API 时,需确保页面在安全上下文中运行(如 HTTPS 或 localhost)。
- 某些浏览器可能要求复制操作由用户触发(如点击事件),否则会拒绝访问剪贴板。
- 对于复杂的富文本内容,可以使用 Clipboard API 的
write方法复制 HTML 或其他格式数据。






