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
若有任何问题,欢迎在下方评论区提出意见。测试