使用隐藏字段将字符串复制到剪贴板
Copy string to clipboard with hidden field
我正在尝试使用本机 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);
}
正如我上面提到的,确实在经过测试的浏览器中工作。但是,它会创建一个 visible 文本输入字段(第 3 行)。我尝试使用 el.style = {position: 'absolute', left: '-9999px'};
,但 Internet Explorer 产生:
Not implemented
我考虑过创建一个 input type="hidden"
,但似乎这个隐藏字段是不可选择的 - 这是有道理的。不用说,此操作会触发 onClick()
,因此确实是用户操作。
关于如何解决这个问题的想法?
而不是使用 el.setAttribute("display", "none");
,您应该将该行更改为:
el.style.display = "none";
为什么这有效?
设置属性 display none 不影响样式。它应该添加为内联样式或在 css 中以隐藏输入框。
我正在尝试使用本机 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);
}
正如我上面提到的,确实在经过测试的浏览器中工作。但是,它会创建一个 visible 文本输入字段(第 3 行)。我尝试使用 el.style = {position: 'absolute', left: '-9999px'};
,但 Internet Explorer 产生:
Not implemented
我考虑过创建一个 input type="hidden"
,但似乎这个隐藏字段是不可选择的 - 这是有道理的。不用说,此操作会触发 onClick()
,因此确实是用户操作。
关于如何解决这个问题的想法?
而不是使用 el.setAttribute("display", "none");
,您应该将该行更改为:
el.style.display = "none";
为什么这有效? 设置属性 display none 不影响样式。它应该添加为内联样式或在 css 中以隐藏输入框。