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);
}
複製代碼
(多謝掘友提出的問題,否則我都沒發現) 上述的代碼適用於非表單元素,若是是表單元素的話,就不須要使用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
若有任何問題,歡迎在下方評論區提出意見。測試