<div id="textContainer"> 内容嘀咕嘀咕大概 </div> <button id="copyButton">一键复制</button> <script> document.getElementById('copyButton').addEventListener('click', function() { const textContainer = document.getElementById('textContainer'); const selection = window.getSelection(); const range = document.createRange(); // 清除之前的选区 selection.removeAllRanges(); // 设置新的选区 range.selectNodeContents(textContainer); selection.addRange(range); // 复制选区的内容到剪贴板 try { const successful = document.execCommand('copy'); console.log(successful ? '复制成功' : '复制失败'); document.execCommand("copy"); // 执行浏览器复制命令 alert("复制成功"); } catch (err) { console.error('复制失败', err); } // 清除选区 selection.removeAllRanges(); }); </script> |