js small daily--copy copy to clipboard

Posted May 26, 20202 min read

The requirements are as follows:click the button to copy the corresponding content to the clipboard
image.png

Solution:Use document.execCommand('copy') to achieve, but pay attention to compatibility.

 <div class = "assistant-wechat"> Little Assistant WeChat:qbxq01 </div>
        <div class = "copy-wechat" onclick = "copyToClipboard('qbxq01')"> Copy WeChat </div>


<script type = "text/javascript">
    function copyToClipboard(text) {
        if(text.indexOf('-')! == -1) {
            let arr = text.split('-');
            text = arr [0]+ arr [1];
        }
        var textArea = document.createElement("textarea");
        textArea.style.position = 'fixed';
        textArea.style.top = '0';
        textArea.style.left = '0';
        textArea.style.width = '2em';
        textArea.style.height = '2em';
        textArea.style.padding = '0';
        textArea.style.border = 'none';
        textArea.style.outline = 'none';
        textArea.style.boxShadow = 'none';
        textArea.style.background = 'transparent';
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.select();

        try {
            var successful = document.execCommand('copy');
            var msg = successful? '<div> Wechat Assistant has been copied </div> <div> Go and add friends to invite you to join the group </div>':'<div> This browser does not support click to copy to clipboard </div> ';
            showAlert(msg)
        } catch(err) {
            showAlert('<div> This browser does not support click to copy to clipboard </div>');
        }

        document.body.removeChild(textArea);
    }
    //Custom prompt box
    function showAlert(str) {
        var alertPart = document.createElement('div');
        alertPart.className = "alert-part";
        alertPart.innerHTML = str;
        document.body.appendChild(alertPart);
        var timeout = setTimeout(function() {
            document.body.removeChild(alertPart);
            clearTimeout(timeout);
        }, 2000)
    }
</script>