小编典典

如何将文本从div复制到剪贴板

javascript

这是我在用户单击此按钮时的代码:

<button id="button1">Click to copy</button>

如何在此div中复制文本?

<div id="div1">Text To Copy</div>

阅读 367

收藏
2020-05-01

共1个答案

小编典典

JAVASCRIPT:

function CopyToClipboard(containerid) {
  if (document.selection) {
    var range = document.body.createTextRange();
    range.moveToElementText(document.getElementById(containerid));
    range.select().createTextRange();
    document.execCommand("copy");
  } else if (window.getSelection) {
    var range = document.createRange();
    range.selectNode(document.getElementById(containerid));
    window.getSelection().addRange(range);
    document.execCommand("copy");
    alert("Text has been copied, now paste in the text-area")
  }
}
<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>
<br /><br />
<div id="div1">Text To Copy </div>
<br />
<textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>
2020-05-01