h5实现点击复制功能
使用document.execCommand方法(兼容旧浏览器)
通过document.execCommand('copy')实现复制功能,需先选中文本内容。创建一个隐藏的textarea或input元素存放目标文本,选中后执行复制命令。

<button onclick="copyText('要复制的文本')">点击复制</button>
<script>
function copyText(text) {
const textarea = document.createElement('textarea');
textarea.value = text;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
alert('复制成功');
}
</script>
使用Clipboard API(现代浏览器推荐)
通过navigator.clipboard.writeText()实现,需注意浏览器兼容性和HTTPS环境限制。该方法返回Promise,可处理复制成功或失败的情况。

<button onclick="copyText('要复制的文本')">点击复制</button>
<script>
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
alert('复制成功');
} catch (err) {
console.error('复制失败:', err);
}
}
</script>
结合Selection API处理复杂内容
若需复制非纯文本内容(如DOM节点内的文本),可通过window.getSelection()选中指定节点内容,再调用复制命令。
<div id="target">这是需要复制的复杂内容</div>
<button onclick="copyElementText('target')">复制DIV内容</button>
<script>
function copyElementText(id) {
const element = document.getElementById(id);
const range = document.createRange();
range.selectNode(element);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand('copy');
window.getSelection().removeAllRanges();
alert('复制成功');
}
</script>
兼容性处理方案
针对不同浏览器环境,可先检测Clipboard API可用性,若不支持则降级使用execCommand。
<script>
async function copyText(text) {
if (navigator.clipboard) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch (err) {
console.warn('Clipboard API失败:', err);
}
}
// 降级方案
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.style.position = 'fixed';
document.body.appendChild(textarea);
textarea.select();
const result = document.execCommand('copy');
document.body.removeChild(textarea);
return result;
}
</script>
注意事项
- 部分浏览器要求复制操作必须由用户手势触发(如click事件)
- iOS Safari对剪贴板操作有额外限制
- HTTP环境下Clipboard API可能不可用
- 可添加视觉反馈(如Toast提示)替代
alert提升体验






