隐藏的元素不会复制到剪贴板

Iva*_*van 3 javascript jquery

我试图添加按钮来复制简单的文本字符串,但没有成功.

function kopiraj() {
  var copyText = document.getElementById("toCopy");
  copyText.select();
  document.execCommand("Copy");
  document.getElementById("telefon").innerHTML = 'Copied';
}
Run Code Online (Sandbox Code Playgroud)
<button type="button" onclick="kopiraj()">Copy</button>
<input type="hidden" id="toCopy" value="123456789">
<p id="telefon"></p>
Run Code Online (Sandbox Code Playgroud)

它没有在剪贴板中放任何东西.

我不需要输入字段.我可以在JS本身添加文本.

ish*_*ood 10

代替的hidden属性,使用一个离屏类和aria-hidden属性(后者可访问性):

.offscreen {
    position: absolute;
    left: -999em;
}

<input ... class="offscreen" aria-hidden="true">
Run Code Online (Sandbox Code Playgroud)


Pat*_*rts 7

你不能.select()隐藏有元素visibility: hidden;display: none;但你可以做这样的事情:

function kopiraj() {
  var copyText = document.getElementById("toCopy");
  copyText.select();
  document.execCommand("Copy");
}
Run Code Online (Sandbox Code Playgroud)
[aria-hidden="true"] {
  opacity: 0;
  position: absolute;
  z-index: -9999;
  pointer-events: none;
}
Run Code Online (Sandbox Code Playgroud)
<button type="button" onclick="kopiraj()">Copy</button>
<input type="text" id="toCopy" value="123456789" aria-hidden="true">
Run Code Online (Sandbox Code Playgroud)

  • @isherwood 那是公平的。我最初打算使用 `#toCopy` 作为选择器,但后来我注意到你的解决方案在我之前发布不久,所以我将选择器更改为可能想要隐藏的内容。 (2认同)