你可以在div的内容上使用document.execCommand('copy')吗?

问题描述:

如果我手动复制html表格,我可以将其粘贴到Google文档中并保留格式(看起来像一张表格)。

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

我如何复制内容以编程方式,使用按钮,并粘贴为HTML表格?如下所示...

How can I copy the contents programmatically, with a button, and paste as an html table? Something like the following...

evar copydeck = $("<div>").html(htmlToInsert);
$('body').append(copydeck);
copydeck.select();
document.execCommand('copy');
copydeck.remove();

以上代码不起作用......但这样做:

The above code does not work...but this does:

copydeck = $("<textarea>").val(this.list.join("\r\n"));
$('body').append(copydeck);
copydeck.select();
document.execCommand('copy');
copydeck.remove();

我想这是因为元素必须是可选择的 - 比如输入或htmlarea字段。但是它们不能保存html(或者它只是纯文本,而不是html)。

I guess it is because the element must be selectable - like an input or htmlarea field. But they can't hold html (or it is just plain text, not html).

任何复制和粘贴HTML的方式?

Any way to copy and paste HTML?

是的!

   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 *!))
  </div>
  <div>
    <input onclick="copy()" type="button" value="Copy">
  </div>