这段时间,某个需求中,有个功能,需要点击一个button复制某段显示出来的text,于是需要自己动手简单封装一个copy方法。
首先,完成复制,必须调用document的一个api:
| 1
 | document.execCommand('copy');
 | 
execCommand的api链接:https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand
这个是必须的,接下来,来介绍下大体思路:
- 在document中建立一个看不见的input
- 把需要复制的文字复制给input的value
- 选择这些文字
- 调用document.execCommand('copy');
在第三步有个兼容性问题,安卓手机可以直接调用input的select方法选中文字,但是iOS调用select方法只会选中,并不会默认选中文字,必须手动执行一个setSelectionRange方法来选中这些文字。否则,iOS上的复制无法生效。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 
 | function copy (text) {var input = document.createElement('input');
 input.setAttribute('readonly', 'readonly');
 input.style.position = 'fixed';
 input.style.top = 0;
 input.style.left = 0;
 input.style.border = 'none';
 input.style.outline = 'none';
 input.style.resize = 'none';
 input.style.background = 'transparent';
 input.style.color = 'transparent';
 input.value = text;
 document.body.appendChild(input);
 if (utils.isIOS()) {
 input.setSelectionRange(0, text.length);
 } else {
 input.select();
 }
 try {
 document.execCommand('copy');
 } catch (err) {
 console.log('unable to copy', err);
 }
 document.body.removeChild(input);
 }
 
 | 
这样一个文本复制的方法就完成了。