【问题标题】:Copy string to clipboard with hidden field使用隐藏字段将字符串复制到剪贴板
【发布时间】:2020-01-30 12:39:12
【问题描述】:

我正在尝试使用本机 JS 将参数字符串复制到我的剪贴板中。到目前为止,这工作正常,但是在 IE 7 中运行我的 sn-p 时,我有一个小问题。

我的代码:

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(),所以确实是一个用户动作。

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

【问题讨论】:

    标签: javascript css internet-explorer


    【解决方案1】:

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

    el.style.display = "none";
    

    为什么会这样? 设置属性 display none 不会影响样式。应添加为内联样式或在 css 中隐藏输入框。

    【讨论】:

      猜你喜欢
      • 2013-11-21
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 2015-10-14
      相关资源
      最近更新 更多