Can you use document.execCommand('copy') on the contents of a div?

前端 未结 1 1948
予麋鹿
予麋鹿 2020-12-20 10:38

If I copy an html table manually, I can paste it into a Google Doc with the formatting preserved (it looks like a table).

How can I copy the contents programmaticall

相关标签:
1条回答
  • 2020-12-20 10:40

    Yes!

       function copy() {
          var target = document.getElementById('my-div');
          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');
          }
        }
      <div id="my-div" style="border:1px dashed #999; color:#666; background:#EEE; padding:2px 5px; margin:10px 0;">
        Hello stackoverflow!))
      </div>
      <div>
        <input onclick="copy()" type="button" value="Copy">
      </div>

    0 讨论(0)
提交回复
热议问题