我有一个网站,其中的邀请链接显示在<h2>
标签内
我只是想在单击文本本身时将文本复制到剪贴板。
我的代码如下:
<script>
function CopyInviteLink() {
var copyText = document.getElementById("invite-link");
copyText.select();
copyText.setSelectionRange(0, 99999)
document.execCommand("copy");
}
function setInviteLink(roomID) {
const inviteLink = window.location.href + "/join.html?room=" + roomID;
document.getElementById("invite-link").innerText = inviteLink;
}
</script>
<h2 id="invite-link" onclick="myFunction()"></h2><br>
我尝试了这种方法: https://www.w3schools.com/howto/howto_js_copy_clipboard.asp
使用以下方法:(document.execCommand("copy")
)
但这似乎仅适用于<input type="text">
,但是我只想使用纯文本,而不是“文本输入”样式
有人可以帮助我或链接解决方案吗?
答案 0 :(得分:1)
const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = document.getElementById("invite-link").innerHTML;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
el.select();
document.execCommand('copy');
alert("Copied the text: " + el.value);
document.body.removeChild(el);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 id="invite-link" onclick="copyToClipboard()">heading</h2><br>
尝试一下:
const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
};
答案 1 :(得分:0)
这将为您服务
这里textToCopy
是input
的值
var input = document.createElement("textarea");
document.body.appendChild(input);
input.value = document.getElementById("invite-link").value;
input.select();
document.execCommand("copy");
document.body.removeChild(input);