The webAPI interface of html5 can easily use just a few lines of code to realize the function of clicking the button to copy the area text, without relying on flash.
/* create a range object */ const range = document.createRange(); range.selectNode(element); // Set the node object contained in the range /* The selection object of the window, representing the text selected by the user */ const selection = window.getSelection(); if(selection.rangeCount > 0) selection.removeAllRanges(); // remove the already contained selected objects selection.addRange(range); // Add the range object of the range to be copied to the selection object document.execCommand('copy'); // Execute the copy command, copy the text selected by the user
example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <article id="article"> <h4>Day trip to the park</h4> <time>2016.8.15 Tuesday</time> <p>It's sunny and sunny today. Xiaohong and I went to People's Park. We played slides, played snowball fights, and rowed boats. What a great day. </p> </article> <button id="copy">Copy Article</button> <textarea style="width: 500px;height: 100px;" placeholder="试一试ctrl + v"></textarea> <script> function copyArticle(event){ const range = document.createRange(); range.selectNode(document.getElementById('article')); const selection = window.getSelection(); if(selection.rangeCount > 0) selection.removeAllRanges(); selection.addRange(range); document.execCommand('copy'); } document.getElementById('copy').addEventListener('click', copyArticle, false); </script> </body> </html>
。