【发布时间】:2017-11-22 16:50:58
【问题描述】:
我想从 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>
复制方法
通过 data-event 和 data-obj 属性调用该方法。
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();
【问题讨论】:
标签: javascript ecmascript-6 clipboard execcommand