我想从 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/