JavaScript 实现点击按钮复制文本到剪贴板
作者:异步漫步时间:2026-10-31 05:37:57浏览:339
本文介绍在 JavaScript 中通过点击按钮将指定文案复制到系统剪贴板的方法。核心方案是利用 document.execCommand('copy') 命令,但需注意不同浏览器的兼容性问题。文章提供了具体的 JS 代码实现示例,包括处理文本格式及创建临时元素等细节,帮助开发者快速集成复制功能。
具体需求场景如下
用户点击特定按钮时,需要将对应的内容复制到系统剪贴板中

技术实现方案
主要依赖 document.execCommand('copy') 方法来完成复制操作,但在实际应用中必须充分考虑浏览器的兼容性问题
<div class="assistant-wechat">小助理微信号:qbxq01</div>
<div class="copy-wechat" onclick="copyToClipboard('qbxq01')">复制微信号</div>相关 JS 代码示例
<script type="text/javascript">
function copyToClipboard(text) {
if (text.indexOf('-') !== -1) {
let arr = text.split('-');
text = arr[0] + arr[1];
}
var textArea = document.createElement("textarea");
textArea.style.position = 'fixed';
textArea.style.top = '0';
textArea.style.left = '0';
textArea.style.width = '2em';
textArea.style.height = '2em';
textArea.style.padding = '0';
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
textArea.style.background = 'transparent';
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? '<div>小助理微信号已复制</div><div>快去加好友邀你入群</div>' : '<div>该浏览器不支持点击复制到剪贴板</div>';
showAlert(msg)
} catch (err) {
showAlert('<div>该浏览器不支持点击复制到剪贴板</div>');
}
document.body.removeChild(textArea);
}
// 自定义提示框
function showAlert(str) {
var alertPart = document.createElement('div');
alertPart.className = "alert-part";
alertPart.innerHTML = str;
document.body.appendChild(alertPart);
var timeout = setTimeout(function () {
document.body.removeChild(alertPart);
clearTimeout(timeout);
}, 2000)
}
</script>以上即为 JavaScript 实现点击复制文案到剪贴板的完整方案,如需了解更多相关技术细节,请参阅本站其他文章
作者最新文章
D3.js 比例尺与坐标轴的配置详解
2026-11-05 16:54:46
JavaScript怎么遍历对象的Symbol键和不可枚举属性
2026-11-05 13:13:39
封装一个健壮的JS字符串判空工具函数
2026-11-05 12:16:14
JavaScript合并数组的三种常用方法:concat、扩展运算符与push
2026-11-05 11:22:29
JavaScript立即执行函数(IIFE)是什么及基本语法
2026-11-05 10:51:19
