js實現選擇及復制粘貼


最近項目有個點擊復制到粘貼板的需求,在這里做一個簡單的例子分享給大家,沒考慮兼容性,需要兼容的大家去查找下文檔

//html
<p id="element">測試測試<p> <botton onclick="copyText(ele)">點擊復制</botton>

  

//js
function copyText(ele) {
  var element = document.querySelecter(ele);

   var selection = window.getSelection();   // 創建Selection 對象

     var range = document.createRange(); //創建Range 對象

          range.selectNodeContents(element); //設定一個目標節點內容的 Range 

          selection.removeAllRanges();  //清空選擇區域

          selection.addRange(range);  //選中元素, 這一步可以實現全選

          document.execCommand("copy"); //復制到粘貼板

     selection.removeAllRanges(); //選擇完成之后清空選擇

          element.oncopy = function(e) { //監聽 復制事件
                e.preventDefault();
                let copyMsg = window.getSelection() + '商業轉載請注明出處。'; // window .getSelection() 表示選擇的內容
                e.clipboardData.setData("Text", copyMsg); // 將復制信息添加到剪切板
         }

}

一個簡單的選擇,復制粘貼就實現啦



 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM