需求如下:点击按钮复制对应内容到剪贴板
方案:利用document.execCommand('copy')来实现,但是要注意兼容性。
<div class="assistant-wechat">小助理微信号:qbxq01</div> <div class="copy-wechat" onclick="copyToClipboard('qbxq01')">复制微信号</div>
<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>