如果您需要简单的逻辑,是否可以将JS嵌入到<a> element to copy static text to the user&#39;s clipboard?

时间:2018-09-09 16:32:54

标签: javascript html css

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!

1 个答案:

答案 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>