是否有可能将JS嵌入到 element to copy static text to the user's clipboard? [closed]中

问题描述 投票:-3回答:1

我想要一个按钮,使用<a>标签,点击它会将静态文本字符串复制到用户的剪贴板,然后将innerHTML更改为“复制!”之类的内容。

这一切都可以在<a>标签内完成,而不需要在其他地方的代码中添加任何额外的脚本吗?

谢谢您的帮助!

javascript html css
1个回答
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>
© www.soinside.com 2019 - 2024. All rights reserved.