简单易懂!让你轻松复制JavaScript内容到剪贴板的代码分享
最编程
2024-02-15 09:08:25
...
引用
直接引用:
<script src="dist/clipboard.min.js"></script>
包: npm install clipboard --save ,然后 import Clipboard from 'clipboard';
使用
从输入框复制
现在页面上有一个 <input>
标签,我们需要复制其中的内容,我们可以这样做:
<input id="demoInput" value="hello world">
<button class="btn" data-clipboard-target="#demoInput">点我复制</button>
import Clipboard from 'clipboard';
const btnCopy = new Clipboard('btn');
注意到,在 <button>
标签中添加了一个 data-clipboard-target
属性,它的值是需要复制的 <input>
的 id
,顾名思义是从整个标签中复制内容。
直接复制
有的时候,我们并不希望从 <input>
中复制内容,仅仅是直接从变量中取值。如果在 Vue
中我们可以这样做:
<button class="btn" :data-clipboard-text="copyValue">点我复制</button>
import Clipboard from 'clipboard';
const btnCopy = new Clipboard('btn');
this.copyValue = 'hello world';
事件
有的时候我们需要在复制后做一些事情,这时候就需要回调函数的支持。
在处理函数中加入以下代码:
// 复制成功后执行的回调函数
clipboard.on('success', function(e) {
console.info('Action:', e.action); // 动作名称,比如:Action: copy
console.info('Text:', e.text); // 内容,比如:Text:hello word
console.info('Trigger:', e.trigger); // 触发元素:比如:<button class="btn" :data-clipboard-text="copyValue">点我复制</button>
e.clearSelection(); // 清除选中内容
});
// 复制失败后执行的回调函数
clipboard.on('error', function(e) {
console.error('Action:', e.action);
console.error('Trigger:', e.trigger);
});
小结
文档中还提到,如果在单页面中使用 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
:表示命令名称,比如:copy
,cut
等 -
aShowDefaultUI
:是否展示用户界面,一般情况下都是false
; -
aValueArgument
:有些命令需要额外的参数,一般用不到;