html5的webAPI接口可以很轻松的使用短短的几行代码就实现点击按钮复制区域文本的功能,不需要依赖flash。
代码如下:
复制代码
1
2
3
4
5
6
7
8
9
10/* 创建range对象 */ const range = document.createRange(); range.selectNode(element); // 设定range包含的节点对象 /* 窗口的selection对象,表示用户选择的文本 */ const selection = window.getSelection(); if(selection.rangeCount > 0) selection.removeAllRanges(); // 将已经包含的已选择的对象清除掉 selection.addRange(range); // 将要复制的区域的range对象添加到selection对象中 document.execCommand('copy'); // 执行copy命令,copy用户选择的文本
复制代码
1
复制代码
1//兼容Pc端的safari浏览器
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18let node = document.getElementById('copy');//input框 node.setAttribute('value', 'hello world'); let issafariBrowser = /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent); if(issafariBrowser){ //safari浏览器单独处理 node.setSelectionRange(0, 9999); } else{ //其他浏览器 const range = document.createRange(); range.selectNode(node); const selection = window.getSelection(); if(selection.rangeCount > 0) selection.removeAllRanges(); selection.addRange(range); } document.execCommand('copy');
还有一种兼容safari和chrome浏览器的通用写法不需要判断,这种写法在demo中可以成功。
demo如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .btn{ cursor: pointer; width: 200px; height: 100px; background: red; display: inline-block; } </style> <!-- <link type="text/css" rel="styleSheet" href="1.css"> --> </head> <body style="background: blue"> <div class="div1"> </div> <div id="cardList"> <div class="btn" id='btn'>点击我,复制我</div> <input id='copy'/> </div> </body> <script> var btn = document.querySelector('#btn'); btn.addEventListener('click',function(){ let input = document.getElementById('copy'); input.setAttribute('readonly', 'readonly'); input.setAttribute('value', 'hello world'); const range = document.createRange(); range.selectNode(input); const selection = window.getSelection(); console.log(selection) if(selection.rangeCount > 0) selection.removeAllRanges(); selection.addRange(range); document.execCommand('copy'); }) </script> </html>
但是在react项目中,在safari浏览器中
window.getSelection();对象的anchorNode值一直为null,
所以在safari中不成功,
所以最终采用了判断是否为safari浏览器来进行不同操作的方法。
API参考:
- document.execCommand
- document.createRange
- window.getSelection
转载于:https://www.cnblogs.com/qdcnbj/p/10145403.html
最后
以上就是花痴狗最近收集整理的关于前端JS复制特定区域的文本(兼容safari)的全部内容,更多相关前端JS复制特定区域内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复