你可以在div的内容上使用document.execCommand('copy')吗? [英] Can you use document.execCommand('copy') on the contents of a div?

查看:262
本文介绍了你可以在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 stackoverflow!))
  </div>
  <div>
    <input onclick="copy()" type="button" value="Copy">
  </div>

这篇关于你可以在div的内容上使用document.execCommand('copy')吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆