【问题标题】:How to copy complete div element to the clipboard using Javasript or Typescript only?如何仅使用 Javascript 或 Typescript 将完整的 div 元素复制到剪贴板?
【发布时间】:2020-08-12 06:03:29
【问题描述】:

我有类似的 html div 元素:

<div id="divTest" style='background-color:grey;'>
Hello
</div>

我想复制完整的 div 元素,而不仅仅是内容“Hello”。

这是我尝试过的,但它只复制内容:

var element = document.getElementById("divTest");

var selection = window.getSelection();
var range = document.createRange();
range.selectNode(element);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("Copy");

如果有人知道如何复制完整的 div 元素??

谢谢

【问题讨论】:

  • 你的意思是要复制div的innerHTML?
  • div复制到剪贴板时的期望
  • @blacksheep 我想粘贴完整的div 然后
  • @BiploveLamichhane 不,我的意思是完整的 div 复制

标签: javascript html css typescript


【解决方案1】:

这就是如何做到的(看看所有没有考虑解决方案就给出负面评价的人)

<div id='myTestELement' style='background-color:grey;'>
Hello
</div>

<input type="text"  id="myInput">
var copyText = document.getElementById("myInput");
copyText.value = document.getElementById("myTestELement").outerHTML;
copyText.select();
copyText.setSelectionRange(0, 99999)
document.execCommand("copy");

这会将html元素以字符串的形式复制到textInput值。

【讨论】:

    【解决方案2】:

    您也可以使用导航界面。

    const element = document.querySelector('#divTest');
    const promise = navigator.clipboard.writeText(element.outerHTML)
    promise.then(
                () => console.log('Success'), 
                () => console.log('Failure')
             )
    

    这比execCommand 更干净,Firefox 已将document.execCommand 声明为过时方法。 为了完全了解navigator.clipboard,请通过Permissions API 了解安全上下文用户同意

    【讨论】:

    • 谢谢。是否也可以复制事件监听器??
    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    相关资源
    最近更新 更多