从 contenteditable div 复制内部文本?

Copy innertext from a contenteditable div?

我知道有一个类似的问题,但是当我尝试时,它不起作用。我发现这是因为我改变了我想复制的 div 上方按钮的位置,但我不知道如何修复它:/我必须说我不理解 JS: /

  function copy() {
      var target = document.getElementById('mydiv');
      var range, select;
      if (document.createRange) {
        range = document.createRange();
        range.selectNode(target)
        select = window.getSelection();
        select.removeAllRanges();
        select.addRange(range);
        document.execCommand('copy');
        select.removeAllRanges();
      } else {
        range = document.body.createTextRange();
        range.moveToElementText(target);
        range.select();
        document.execCommand('copy');
      }
    }
#mydiv{
border: solid black 1px;
border-radius: 4x;
margin: 10px 0px;
}
<input onclick="copy()" type="button" value="Copy" />
<p></p>
<div>Insert text below</div>
<div id="mydiv" contenteditable="true"></div>

使用 range.selectNodeContents(target) 而不是 range.selectNode(target) 来避免复制 outerHTML

  function copy() {
      var target = document.getElementById('mydiv');
      var range, select;
      if (document.createRange) {
        range = document.createRange();
        range.selectNodeContents(target)
        select = window.getSelection();
        select.removeAllRanges();
        select.addRange(range);
        document.execCommand('copy');
        select.removeAllRanges();
      } else {
        range = document.body.createTextRange();
        range.moveToElementText(target);
        range.select();
        document.execCommand('copy');
      }
    }
#mydiv{
border: solid black 1px;
border-radius: 4x;
margin: 10px 0px;
}
<input onclick="copy()" type="button" value="Copy" />
<p></p>
<div>Insert text below</div>
<div id="mydiv" contenteditable="true"></div>