复制剪切板功能

分享一个前端复制剪贴板的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;
  }
}
复制代码
相关文章
相关标签/搜索