分享一个前端复制剪贴板的util方法,相比较30seconds上提供的功能,这个util还采用了navigator.clipboard
的API;javascript
首先看一下navigator.clipboard
的兼容性:前端
navigator.clipboard
的功能能够覆盖到89.13%;在navigator.clipboard
不能生效的时候,就能够采用document.execCommand
java
在来看一下document.execCommand
的兼容性: 能够覆盖达到95.41%的用户,相比较而言
document.execCommand
对于低版本和IE的兼容性会更好。markdown
下你那就是功能的实现了:app
let __textArea;
function getTextArea() {
if (!__textArea) {
__textArea = document.createElement('textarea');
__textArea.style.position = 'fixed';
__textArea.style.left = '100vw';
__textArea.style.top = 0;
}
return __textArea;
}
export default class ClipboardUtils {
static async copyTextToClipboard(text) {
if (navigator.clipboard) {
return navigator.clipboard.writeText(text);
}
// Fallback
const textArea = getTextArea();
textArea.value = text;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
const success = document.execCommand('copy');
document.body.removeChild(textArea);
if (!success) {
throw new Error('复制至剪贴簿失败');
}
return success;
}
}
复制代码