JavaScript 复制内容到剪贴板

最近一个活动页面中有一个小需求,用户点击或者长按就能够复制内容到剪贴板,记录一下实现过程和遇到的坑。ios

常见方法

查了一下万能的Google,如今常见的方法主要是如下两种:git

  • 第三方库:clipboard.jsgithub

  • 原生方法:document.execCommand()npm

分别来看看这两种方法是如何使用的。浏览器

clipboard.js

这是clipboard的官网:https://clipboardjs.com/,看起来就是这么的简单。app

引用

直接引用: <scriptsrc="dist/clipboard.min.js"></script>函数

包: npm install clipboard--save ,而后 importClipboardfrom'clipboard';this

使用

从输入框复制spa

如今页面上有一个 <input> 标签,咱们须要复制其中的内容,咱们能够这样作:调试

  1. <input id="demoInput" value="hello world">

  2. <button class="btn" data-clipboard-target="#demoInput">点我复制</button>

  1. import Clipboard from 'clipboard';

  2. const btnCopy = new Clipboard('btn');

注意到,在 <button> 标签中添加了一个 data-clipboard-target 属性,它的值是须要复制的 <input>id,顾名思义是从整个标签中复制内容。

直接复制

有的时候,咱们并不但愿从 <input> 中复制内容,仅仅是直接从变量中取值。若是在 Vue 中咱们能够这样作:

  1. <button class="btn" :data-clipboard-text="copyValue">点我复制</button>

 

  1. import Clipboard from 'clipboard';

  2. const btnCopy = new Clipboard('btn');

  3. this.copyValue = 'hello world';

事件

有的时候咱们须要在复制后作一些事情,这时候就须要回调函数的支持。

在处理函数中加入如下代码:

  1. // 复制成功后执行的回调函数

  2. clipboard.on('success', function(e) {

  3.    console.info('Action:', e.action); // 动做名称,好比:Action: copy

  4.    console.info('Text:', e.text); // 内容,好比:Text:hello word

  5.    console.info('Trigger:', e.trigger); // 触发元素:好比:<button class="btn" :data-clipboard-text="copyValue">点我复制</button>

  6.    e.clearSelection(); // 清除选中内容

  7. });

  8.  

  9. // 复制失败后执行的回调函数

  10. clipboard.on('error', function(e) {

  11.    console.error('Action:', e.action);

  12.    console.error('Trigger:', e.trigger);

  13. });

小结

文档中还提到,若是在单页面中使用 clipboard ,为了使得生命周期管理更加的优雅,在使用完以后记得 btn.destroy() 销毁一下。

clipboard 使用起来是否是很简单。可是,就为了一个 copy 功能就使用额外的第三方库是否是不够优雅,这时候该怎么办?那就用原生方法实现呗。

document.execCommand()方法

先看看这个方法在 MDN 上是怎么定义的:

which allows one to run commands to manipulate the contents of the editable region.

意思就是能够容许运行命令来操做可编辑区域的内容,注意,是可编辑区域

定义

bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)

方法返回一个 Boolean 值,表示操做是否成功。

  • aCommandName :表示命令名称,好比: copycut 等(更多命令见命令);

  • aShowDefaultUI:是否展现用户界面,通常状况下都是 false

  • aValueArgument:有些命令须要额外的参数,通常用不到;

兼容性

这个方法在以前的兼容性实际上是不太好的,可是好在如今已经基本兼容全部主流浏览器了,在移动端也可使用。

使用

从输入框复制

如今页面上有一个 <input> 标签,咱们想要复制其中的内容,咱们能够这样作:

  1. <input id="demoInput" value="hello world">

  2. <button id="btn">点我复制</button>

  1. const btn = document.querySelector('#btn');

  2. btn.addEventListener('click', () => {

  3.    const input = document.querySelector('#demoInput');

  4.    input.select();

  5.    if (document.execCommand('copy')) {

  6.        document.execCommand('copy');

  7.        console.log('复制成功');

  8.    }

  9. })

其它地方复制

有的时候页面上并无 <input> 标签,咱们可能须要从一个 <div> 中复制内容,或者直接复制变量。

还记得在 execCommand() 方法的定义中提到,它只能操做可编辑区域,也就是意味着除了 <input><textarea> 这样的输入域之外,是没法使用这个方法的。

这时候咱们须要曲线救国。

  1. <button id="btn">点我复制</button>

  1. const btn = document.querySelector('#btn');

  2. btn.addEventListener('click',() => {

  3.    const input = document.createElement('input');

  4.    document.body.appendChild(input);

  5.     input.setAttribute('value', '据说你想复制我');

  6.    input.select();

  7.    if (document.execCommand('copy')) {

  8.        document.execCommand('copy');

  9.        console.log('复制成功');

  10.    }

  11.    document.body.removeChild(input);

  12. })

算是曲线救国成功了吧。在使用这个方法时,遇到了几个坑。

遇到的坑

在Chrome下调试的时候,这个方法时完美运行的。而后到了移动端调试的时候,坑就出来了。

对,没错,就是你,ios。。。

1.点击复制时屏幕下方会出现白屏抖动,仔细看是拉起键盘又瞬间收起

知道了抖动是因为什么产生的就比较好解决了。既然是拉起键盘,那就是聚焦到了输入域,那只要让输入域不可输入就行了,在代码中添加 input.setAttribute('readonly','readonly');使这个 <input>是只读的,就不会拉起键盘了。

2.没法复制

这个问题是因为 input.select() 在ios下并无选中所有内容,咱们须要使用另外一个方法来选中内容,这个方法就是 input.setSelectionRange(0,input.value.length);

完整代码以下:

  1. const btn = document.querySelector('#btn');

  2. btn.addEventListener('click',() => {

  3.    const input = document.createElement('input');

  4.    input.setAttribute('readonly', 'readonly');

  5.    input.setAttribute('value', 'hello world');

  6.    document.body.appendChild(input);

  7.    input.setSelectionRange(0, 9999);

  8.    if (document.execCommand('copy')) {

  9.        document.execCommand('copy');

  10.        console.log('复制成功');

  11.    }

  12.    document.body.removeChild(input);

  13. })

总结

以上就是关于JavaScript如何实现复制内容到剪贴板,附上几个连接:

  • execCommand MDN:https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

  • execCommand兼容性:https://caniuse.com/#search=execCommand

  • clipboard.js:https://github.com/zenorocha/clipboard.js