需求以下:點擊按鈕複製對應內容到剪貼板javascript
方案:利用document.execCommand('copy')來實現,可是要注意兼容性。java
<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>