複製剪切板功能

分享一個前端複製剪貼板的util方法,相比較30seconds上提供的功能,這個util還採用了navigator.clipboard的API;javascript

首先看一下navigator.clipboard的兼容性:前端

navigator.clipboard的功能能夠覆蓋到89.13%;在navigator.clipboard不能生效的時候,就能夠採用document.execCommandjava

在來看一下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;
  }
}
複製代碼
相關文章
相關標籤/搜索