9行代碼實現複製內容至剪切板

Demo: ma125120.github.io/ma-dom/test…html

本方法主要使用了 Range 對象和HTML5的Selection API,通過測試,本方法在主流瀏覽器如谷歌瀏覽器、火狐瀏覽器、360安全瀏覽器、搜狗高速瀏覽器中均運行良好。git

先附上你們最想看的代碼:github

function copy(el) {
	var range = document.createRange();
	var end = el.childNodes.length;
	range.setStart(el,0);
	range.setEnd(el,end);

	var selection = window.getSelection();
	selection.removeAllRanges();
	selection.addRange(range);
	document.execCommand("copy",false,null);
	selection.removeRange(range);
}
複製代碼

實現步驟

  1. 首先是利用**document.createRange()**建立一個 Range 對象 ,而後獲取所需複製元素的子元素的長度大小,而後調用Range對象的setStart和setEnd方法設置選擇區域的大小。
  2. 此時只是設置了選擇區域的大小,實際上在window中並無真正選中,因此還須要調用window.getSelection()生成一個 Selection 對象,在添加選區以前最好先調用selection.removeAllRanges()清除其餘的選區,不然瀏覽器可能會發出下面的警告,而後再調用 Selection 對象的addRange方法,將上一步的 range 做爲參數傳入,便可將所需複製的元素真正設置爲被選擇區域。
  3. 如今就能夠像平時選中文字後調用document.execCommand來實現將被選擇區域的文字複製到剪貼板。
  4. 最後還須要調用 Selection 對象的removeRange方法將 Range 對象移除,保證被選擇區域永遠只有一個被選擇的元素,不然某些瀏覽器在下次可能會由於有兩個被選擇元素而發出警告或者報錯。

其餘狀況

(多謝掘友提出的問題,否則我都沒發現) 上述的代碼適用於非表單元素,若是是表單元素的話,就不須要使用Selection API了,只須要使用el.select(); document.execCommand("copy",false,null);便可,合併到一塊兒即爲chrome

function copy(el) {
    if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
        el.select();
    } else {
        var range = document.createRange();
    	var end = el.childNodes.length;
    	range.setStart(el,0);
    	range.setEnd(el,end);
    
    	var selection = window.getSelection();
    	selection.removeAllRanges();
    	selection.addRange(range);
    }
	
	document.execCommand("copy",false,null);
	range && selection.removeRange(range);
}
複製代碼

注意

--瀏覽器

調用該功能時,必須是在點擊按鈕後或者是點擊 帶有user-select: none屬性的元素,不然瀏覽器可能會發出這樣的警告:[Deprecation] The behavior that Selection.addRange() merges existing Range and the specified Range was removed. See www.chromestatus.com/features/66… for more details.安全

最後附上github地址:github.com/ma125120/ma…bash

後續補充

該功能其實還比較基礎,若是想使用更完成一點的功能,好比複製完內容後在尾部添加一些額外的文本,則可使用我另一個庫中的功能,copy.js。使用方法readme.md中有介紹。dom

若有任何問題,歡迎在下方評論區提出意見。測試

相關文章
相關標籤/搜索