我想要一个按钮,使用<a>
标签,点击它会将静态文本字符串复制到用户的剪贴板,然后将innerHTML更改为“复制!”之类的内容。
这一切都可以在<a>
标签内完成,而不需要在其他地方的代码中添加任何额外的脚本吗?
谢谢您的帮助!
这是工作代码,
function SelectText(element) {
var doc = document
, text = doc.getElementById(element)
, range, selection;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
function copyToClipboard() {
SelectText('copy_to_clipboard');
document.execCommand('copy');
document.getSelection().removeAllRanges();
document.getElementById("msg").style.display="block";
}
#btn_select{
cursor:pointer;
}
<div><p id="copy_to_clipboard">Some text goes here!</p><p id="msg" style="display: none;">Copied!</p></div>
<a id="btn_select" onclick="copyToClipboard();">Click me!</a>