JavaScript 实现点击按钮复制文本到剪贴板

作者:异步漫步

时间:2026-10-31

浏览:338

本文介绍在 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 实现点击复制文案到剪贴板的完整方案,如需了解更多相关技术细节,请参阅本站其他文章

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章