分享一個前端複製剪貼板的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;
}
}
複製代碼