JavaScript复制到剪贴板仅工作一次

时间:2018-07-08 16:51:04

标签: javascript

试图四处查看,但未找到解决方案。我正在使用此JS:

function copy(containerid) {
    var range = document.createRange();
    document.getElementById(containerid).style.display = "block";
    range.selectNode(document.getElementById(containerid));
    window.getSelection().addRange(range);
    document.execCommand("Copy");
    document.getElementById(containerid).style.display = "none";
}

但是我只能在视图中使用它一次,或者containeid保持相同的值。我的看法:

<input type="text" value="x1" id="x1" style="display:none"><input type="text" value="x2" id="x2" style="display:none">
<img src="~/images/new-post-16.png" onclick="copy('x1')"/> <img src="~/images/phone-30-16.png" onclick="copy('x2')" />

我试图乘以该函数并仅对一个元素调用它,但是它仍然仅复制了一个实例,无论是x1还是重新加载页面x2之后。有任何想法吗?元素必须隐藏。

2 个答案:

答案 0 :(得分:1)

您正在尝试将选择添加到其他控件中已存在的选择中。那是行不通的。基本上,您正在尝试在两个不同的文本输入中使用多光标。

如果您在window.getSelection().removeAllRanges();之前用window.getSelection().addRange(range);清除选择,它将起作用。

这也是@Hari Das代码起作用的原因:selectAll 替换所选范围,它不会尝试添加它。

答案 1 :(得分:0)

尝试以下。可以。

FileTester
function copy(containerid) {   
    var copyDiv = document.getElementById(containerid);
    copyDiv.style.display = 'block';
    copyDiv.focus();
    document.execCommand('SelectAll');
    document.execCommand("Copy", false, null);
    copyDiv.style.display = 'none';
    console.log("Text value copied to clipboard from ID: ", containerid);
}