实用工具函数之文本复制粘贴

91 阅读1分钟

概述

日常项目开发者,时不时会碰到文本复制粘贴的功能,这么小个功能点就不需要用到库,其实实现过程也很难简单,这里记录下,方便下次使用。

实现

function copyTextToClipBoard(text: string): Promise<any> {
  const textArea = document.createElement('textarea');
  textArea.style.position = 'fixed';
  textArea.style.top = '-10em';
  textArea.style.left = '-10em';
  textArea.style.width = '2em';
  textArea.style.height = '2em';
  textArea.style.padding = '0';
  textArea.style.border = 'none';
  textArea.style.outline = 'none';
  textArea.style.boxShadow = 'none';
  textArea.style.background = 'transparent';
  textArea.value = text;
  document.body.appendChild(textArea);
  textArea.select();

  let result;
  try {
    const successful = document.execCommand('copy');
    result = successful ? Promise.resolve() : Promise.reject(new Error('exec copy failed'));
  } catch (err) {
    result = Promise.reject(err);
  }
  document.body.removeChild(textArea);

  return result;
}