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用戶選擇的文本測試:
瀏覽器的版本號為我測試時使用的版本。
edge瀏覽器、Chrome(v54.0.2840.99 m)、Firefox(v49.0.1)可用。
IE9、IE10、IE11會彈出提示詢問是否將文本粘貼到剪貼板上。
IE7、IE8不支持該功能。
IOS10的Safari瀏覽器可用。
根據反饋,IOS9以下的Safari瀏覽器應該是不支持該功能的。
Demo:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title></head><body><article id="article"><h4>公園一日游</h4><time>2016.8.15 星期二</time><p>今天風和日麗,我和小紅去了人民公園,玩了滑梯、打雪仗、劃船,真是愉快的一天啊。</p></article><button id="copy">復制文章</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>以上所述是小編給大家介紹的JavaScript實現點擊按鈕復制指定區域文本,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答