9行代码实现复制内容至剪切板

6,133 阅读2分钟

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

本方法主要使用了 Range 对象和HTML5的Selection API,经过测试,本方法在主流浏览器如谷歌浏览器、火狐浏览器、360安全浏览器、搜狗高速浏览器中均运行良好。

先附上大家最想看的代码:

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);即可,合并到一起即为

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…

后续补充

该功能其实还比较基础,如果想使用更完成一点的功能,比如复制完内容后在尾部添加一些额外的文本,则可以使用我另外一个库中的功能,copy.js。使用方法readme.md中有介绍。

如有任何问题,欢迎在下方评论区提出意见。