注意css中的样式,有些页面复制不成功就是没有添加那一句造成的。
代码块
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <style type="text/css"> *{ -webkit-user-select: auto; } </style> <body> <span> 你好,好久不见! </span> <button>复制</button> <script> function copyArticle(event) { const range = document.createRange(); range.selectNode(document.getElementById('content')); const selection = window.getSelection(); if(selection.rangeCount > 0) selection.removeAllRanges(); selection.addRange(range); document.execCommand('copy'); alert("复制成功!"); } document.getElementById('copyBT').addEventListener('click', copyArticle, false); </script> </body> </html>