I'd like to have a button, using an <a>
tag, where clicking on it copies a static string of text to the user's clipboard, then changes the innerHTML to say something like 'Copied!'
Is this all possible to do within the <a>
tag, without any extra scripts needed to be put in the code elsewhere?
Thank you for your help!
答案 0 :(得分:1)
这是工作代码,
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>