欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript復制文案到剪貼板小技巧

 更新時間:2023年07月31日 10:49:32   作者:半畝花田  
這篇文章主要為大家介紹了JavaScript復制文案到剪貼板實現(xiàn)小技巧,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

需求如下

點擊按鈕復制對應內(nèi)容到剪貼板

方案

利用document.execCommand('copy')來實現(xiàn),但是要注意兼容性。

<div class="assistant-wechat">小助理微信號:qbxq01</div>
        <div class="copy-wechat" onclick="copyToClipboard('qbxq01')">復制微信號</div>

 JS

<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>小助理微信號已復制</div><div>快去加好友邀你入群</div>' : '<div>該瀏覽器不支持點擊復制到剪貼板</div>';
            showAlert(msg)
        } catch (err) {
            showAlert('<div>該瀏覽器不支持點擊復制到剪貼板</div>');
        }
        document.body.removeChild(textArea);
    }
    // 自定義提示框
    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>

以上就是JavaScript復制文案到剪貼板小技巧的詳細內(nèi)容,更多關(guān)于JavaScript復制文案剪貼板的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論