如何将计算值复制到剪贴板?

How to copy a calculated value to clipboard?

我有一个计算值的公式。这个值我想插入到 Excel sheet。为了让用户感到舒适,我想自动将其放入剪贴板。

我尝试在 JS 中完成我的第一步并遇到了这个(可能)非常简单的问题。但是我发现的所有方法都与 html 输入标签的原始值有关。我从未见过任何从在 js 中创建的值复制到剪贴板的函数。

var EEFactor = 1*1; // just a formula to calculate a value
copyValue2Clipboard(EEFactor);

function value2Clipboard(value) {
// please help
}
const copyToClipboard = str => {
  const el = document.createElement('textarea');  // Create a <textarea> element

  el.value = str;                                 // Set its value to the string that you want copied

  el.setAttribute('readonly', '');                // Make it readonly to be tamper-proof

  el.style.position = 'absolute';                 
  el.style.left = '-9999px';                      // Move outside the screen to make it invisible

  document.body.appendChild(el);                  // Append the <textarea> element to the HTML document

  const selected =            
      document.getSelection().rangeCount > 0        // Check if there is any content selected previously
      ? document.getSelection().getRangeAt(0)     // Store selection if found
      : false;                                    // Mark as false to know no selection existed before

  el.select();                                    // Select the <textarea> content

  document.execCommand('copy');                   // Copy - only works as a result of a user action (e.g. click events)

  document.body.removeChild(el);                  // Remove the <textarea> element

  if (selected) {                                 // If a selection existed before copying

    document.getSelection().removeAllRanges();    // Unselect everything on the HTML document

    document.getSelection().addRange(selected);   // Restore the original selection

  }
};

这样试试。

function copyToClipboard(str) {
  var el = document.createElement('textarea');
   // Set value (string to be copied)
   el.value = str;
   // Set non-editable to avoid focus and move outside of view
   el.setAttribute('readonly', '');
   el.style = {position: 'absolute', left: '-9999px'};
   document.body.appendChild(el);
   // Select text inside element
   el.select();
   // Copy text to clipboard
   document.execCommand('copy');
   // Remove temporary element
   document.body.removeChild(el);
};

var EEFactor = 1*1;

copyToClipboard(EEFactor);

有一个很好解释的例子here