js 实现复制
使用 document.execCommand 方法(已废弃但仍可用)
此方法兼容较旧浏览器,但现代规范已标记为废弃。
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(现代推荐方式)
Navigator.clipboard API 是当前标准方法,需注意浏览器安全限制(通常要求 HTTPS 或 localhost)。

async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
console.log('复制成功');
} catch (err) {
console.error('复制失败:', err);
}
}
处理无权限情况
添加降级方案,当 Clipboard API 不可用时自动回退到传统方法:

async function copyText(text) {
if (!navigator.clipboard) {
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);
return;
}
try {
await navigator.clipboard.writeText(text);
console.log('复制成功');
} catch (err) {
console.error('复制失败:', err);
}
}
复制特定元素内容
复制 DOM 元素内的文本内容(如 div 内的文字):
async function copyElementText(elementId) {
const element = document.getElementById(elementId);
if (element) {
await copyText(element.innerText);
}
}
添加用户反馈
复制操作后建议显示视觉反馈:
async function copyWithFeedback(text, feedbackElement) {
await copyText(text);
if (feedbackElement) {
feedbackElement.textContent = '已复制!';
setTimeout(() => {
feedbackElement.textContent = '';
}, 2000);
}
}
注意事项
- 某些浏览器可能要求复制操作必须由用户手势(如点击事件)触发
- iOS Safari 对 Clipboard API 的支持有特殊限制
- 在 iframe 中可能需要额外权限配置
- 错误处理应包含权限拒绝(PermissionDenied)的情况






