使用隐藏字段将字符串复制到剪贴板

时间:2019-10-01 08:44:02

标签: javascript css internet-explorer

我正在尝试使用本机JS将参数字符串复制到剪贴板中。到目前为止,这种方法还可以,但是在IE 7中运行我的代码段时,我还是遇到了一个小问题。

我的代码:

function copyStringToClipboard (str) {
    // Create new element
    var el = document.createElement('input');
    el.setAttribute("display", "none");
    el.setAttribute("type", "text");
    el.value = str;
    el.setAttribute('readonly', '');
    document.body.appendChild(el);
    el.select();
    // Copy text to clipboard
    document.execCommand('copy');
    // Remove temporary element
    document.body.removeChild(el);
}

如上所述,该确实在经过测试的浏览器中有效。但是,它会创建一个可见文本输入字段(第3行)。我尝试使用el.style = {position: 'absolute', left: '-9999px'};,但Internet Explorer产生:

  

未实现

我曾考虑过创建input type="hidden",但似乎该隐藏字段是不可选择的-这很有意义。不用说,此操作会触发onClick(),因此实际上是通过用户操作触发的。

关于如何解决此问题的想法?

1 个答案:

答案 0 :(得分:1)

而不是使用el.setAttribute("display", "none");,您应该将该行更改为:

el.style.display = "none";

为什么这样? 设置属性显示为none不会影响样式。应该将其添加为嵌入式样式或添加到CSS中以隐藏输入框。