我试图添加按钮来复制简单的文本字符串,但没有成功.
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)
你不能.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)