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

前端 未结 1 1955
予麋鹿
予麋鹿 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');
          }
        }
      
    Hello stackoverflow!))

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