1. 程式人生 > >copyToClipboard - 復制到剪貼板advanced

copyToClipboard - 復制到剪貼板advanced

lang comm lec select tor 填充 pen eal 事件

將一個字符串復制到剪貼板。 僅作為用戶操作的結果(即,在 click 事件偵聽器中)。

創建一個新的 <textarea> 元素,用提供的數據填充它,並將其添加到 HTML 文檔中。 使用 Selection.getRangeAt() 來存儲選擇的範圍(如果有的話)。 使用 document.execCommand(‘copy‘) 復制到剪貼板。 從HTML文檔中刪除 <textarea> 元素。 最後,使用 Selection().addRange() 來恢復原始選擇範圍(如果有的話)。

const copyToClipboard = str => {
  const el = document.createElement(‘textarea‘);
  el.value = str;
  el.setAttribute(‘readonly‘, ‘‘);
  el.style.position = ‘absolute‘;
  el.style.left = ‘-9999px‘;
  document.body.appendChild(el);
  const selected =
    document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
  el.select();
  document.execCommand(‘copy‘);
  document.body.removeChild(el);
  if (selected) {
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(selected);
  }
};

copyToClipboard(‘Lorem ipsum‘); // ‘Lorem ipsum‘ copied to clipboard.

copyToClipboard - 復制到剪貼板advanced