Как мне скопировать html div, как мышью, выбрать и скопировать, а затем вставить его куда угодно. В angular 8 - PullRequest
0 голосов
/ 25 февраля 2020

Я пытался ...


    const selBox = document.createElement('textarea');
    const selBox1 = (selBox);
    selBox1.style.position = 'fixed';
    selBox1.style.left = '0';
    selBox1.style.top = '0';
    selBox1.style.opacity = '0';
    selBox1.value = val;
    document.body.appendChild(selBox);
    selBox1.focus();
    selBox1.select();
    document.execCommand('copy');
    document.body.removeChild(selBox)

Но он копирует только внутреннее текстовое значение. И я хочу полный div с тем же CSS свойством. Для вставки на почту или другое место.

1 Ответ

0 голосов
/ 26 февраля 2020

CopyFunction=()=> {
  const elm = document.getElementById("copyCodeId");
  // for Internet Explorer

  if (document.body.createTextRange) {
    const range = document.body.createTextRange();
    range.moveToElementText(elm);
    range.select();
    document.execCommand("copy");
    alert("Copied div content to clipboard");
  } else if (window.getSelection) {
    // other browsers

    const selection = window.getSelection();
    const range = document.createRange();
    range.selectNodeContents(elm);
    selection.removeAllRanges();
    selection.addRange(range);
    document.execCommand("copy");
    alert("Copied div content to clipboard");
  }
}
<div class="code-bg" id="copyCodeId">
  Click on the button to copy the text from the div element. Try to paste the text<span style="color:red"> (e.g. ctrl+v)</span> afterwards in a different window, to see the effect.
</div>
<button onclick="CopyFunction()">Copy div</button>
...