简体   繁体   English

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

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

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表,则可以将其粘贴到保留格式(看起来像表)的Google文档中。

How can I copy the contents programmatically, with a button, and paste as an html table? 如何使用按钮以编程方式复制内容并将其粘贴为html表? 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();

I guess it is because the element must be selectable - like an input or htmlarea field. 我猜这是因为元素必须是可选的-就像输入或htmlarea字段一样。 But they can't hold html (or it is just plain text, not html). 但是他们不能保存html(或者只是纯文本,而不是html)。

Any way to copy and paste HTML? 有什么办法复制和粘贴HTML?

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM