使用 execCommand 的 javascript 副本

标签 javascript ecmascript-6 clipboard execcommand

我想从 html 元素的数据集中复制一些内容。

HTML 代码

<p id="web-password-@{{ id }}" data-password="@{{ password }}" 
data-state="0">@{{ hidePassword }}</p>

<button class="mdl-button mdl-js-button mdl-button--icon">

    <i data-event="copy" data-obj="util" data-target="web-password-@{{ id }}" 
    class="material-icons clickable-icon">content_copy</i>

</button>

复制方法

正在通过数据事件和数据对象属性调用该方法。

copy (args) {

    let copyText = document.getElementById(args.target).dataset.password;

    console.log(copyTest); // output: specific password

    document.execCommand("Copy");
}

像这样它不会将内容复制到剪贴板。有人看到错误了吗?

更新

以下代码适用于 html 元素的实际 textContent。

但我需要从 data-password 属性中复制值

let range = document.createRange();

let selection = window.getSelection();

let node = document.getElementById(args.target);

range.selectNodeContents(node);

selection.removeAllRanges();

selection.addRange(range);

document.execCommand("copy");

可能的解决方案

所以我将值写入一个隐藏的输入字段,选择它,复制它并再次删除临时隐藏的输入字段。

但它不复制任何东西。?

let copyValue = document.getElementById(args.target).dataset.password;

document.body.insertAdjacentHTML('beforeend', `<input hidden id="temp-copy" value="${copyValue}">`);

let copyText = document.getElementById('temp-copy');

copyText.select();

document.execCommand("copy");

copyText.remove();

最佳答案

解决方案

更新

更好的解决方案。

copyPassword (args) {

    function handler(event) {

        event.clipboardData.setData('text/plain', document.getElementById(args.target).dataset.password);

        event.preventDefault();

        document.removeEventListener('copy', handler, true);
    }

    document.addEventListener('copy', handler, true);

    document.execCommand('copy');
}

备选方案。 这也有效。

let range = document.createRange();

let selection = window.getSelection();

let password = document.getElementById(args.target).dataset.password;

document.body.insertAdjacentHTML('beforeend', `<p id="temp-copy">${password}</p>`);

let node = document.getElementById('temp-copy');

range.selectNodeContents(node);

selection.removeAllRanges();

selection.addRange(range);

document.execCommand("copy");

document.getElementById('temp-copy').remove();

关于使用 execCommand 的 javascript 副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44648049/

相关文章:

javascript - 任意类型的函数调用

javascript - 如何从 browserify/babelify 导出全局变量以便在没有 browserify 的项目中使用?

python - 使用 Tkinter 将输出复制到剪贴板的按钮

javascript - 使用JavaScript获取div背景图片的实际大小

javascript - 纯 JavaScript - 点击外部时隐藏 Div

javascript - JS Slide 切换侧边栏并展开内容 div

javascript - 根据键值比较合并两个对象数组

javascript - 使用 immutablejs 更新列表中的名称

java - 复制/粘贴在签名的小程序中不起作用

javascript - 在 Rails 中,如何在 HTML 页面上将 javascript 显示为文本?