html5的webAPI接口可以很輕松的使用短短的幾行代碼就實現點擊按鈕復制區域文本的功能,不需要依賴flash。
代碼如下:
/* 創建range對象 */ const range = document.createRange(); range.selectNode(element); // 設定range包含的節點對象 /* 窗口的selection對象,表示用戶選擇的文本 */ const selection = window.getSelection(); if(selection.rangeCount > 0) selection.removeAllRanges(); // 將已經包含的已選擇的對象清除掉 selection.addRange(range); // 將要復制的區域的range對象添加到selection對象中 document.execCommand('copy'); // 執行copy命令,copy用戶選擇的文本
//兼容Pc端的safari瀏覽器
let node = document.getElementById('copy');//input框 node.setAttribute('value', 'hello world'); let issafariBrowser = /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent); if(issafariBrowser){ //safari瀏覽器單獨處理 node.setSelectionRange(0, 9999); } else{ //其他瀏覽器 const range = document.createRange(); range.selectNode(node); const selection = window.getSelection(); if(selection.rangeCount > 0) selection.removeAllRanges(); selection.addRange(range); } document.execCommand('copy');
還有一種兼容safari和chrome瀏覽器的通用寫法不需要判斷,這種寫法在demo中可以成功。
demo如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .btn{ cursor: pointer; width: 200px; height: 100px; background: red; display: inline-block; } </style> <!-- <link type="text/css" rel="styleSheet" href="1.css"> --> </head> <body style="background: blue"> <div class="div1"> </div> <div id="cardList"> <div class="btn" id='btn'>點擊我,復制我</div> <input id='copy'/> </div> </body> <script> var btn = document.querySelector('#btn'); btn.addEventListener('click',function(){ let input = document.getElementById('copy'); input.setAttribute('readonly', 'readonly'); input.setAttribute('value', 'hello world'); const range = document.createRange(); range.selectNode(input); const selection = window.getSelection(); console.log(selection) if(selection.rangeCount > 0) selection.removeAllRanges(); selection.addRange(range); document.execCommand('copy'); }) </script> </html>
但是在react項目中,在safari瀏覽器中
window.getSelection();對象的anchorNode值一直為null,
所以在safari中不成功,
所以最終采用了判斷是否為safari瀏覽器來進行不同操作的方法。
API參考: