我想从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>复制方法
该方法是通过数据事件和数据obj属性调用的。
copy (args) {
let copyText = document.getElementById(args.target).dataset.password;
console.log(copyTest); // output: specific password
document.execCommand("Copy");
}这样,它就不会将内容复制到剪贴板上。有人看到错误了吗?
更新
下面的代码适用于actual元素的实际textContent。
,但我需要从数据密码属性复制值。
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();发布于 2017-06-20 11:59:08
溶液
更新
更好的解决方案。
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();发布于 2017-06-20 09:06:13
复制命令将当前所选内容复制到剪贴板。因此,在复制之前,需要在输入中选择文本:
let input = document.getElementById(args.target);
input.select();
document.execCommand("Copy");如果不支持或启用命令,您还可能希望检查execCommand的返回值,即false。
更新
如果要复制的节点不是input或textarea,您可以选择它的文本如下:
var range = document.createRange();
var selection = window.getSelection();
range.selectNodeContents(document.getElementById('p'));
selection.removeAllRanges();
selection.addRange(range);https://stackoverflow.com/questions/44648049
复制相似问题