為你的網(wǎng)站博客添加代碼塊復制功能

純JS無需第三方插件,各類網(wǎng)站皆可通用,為你網(wǎng)站添加復制代碼功能。思路很簡單:
遍歷pre標簽給每個標簽命名id,然后通過雙擊事件調用復制方法實現(xiàn)最簡單代碼復制

<script>
    window.onload = function () {
        let preItems = document.getElementsByTagName('pre');
        for (let index in preItems) {
            let preItem = preItems[index];
            preItem.setAttribute("id", index);
            preItem.setAttribute("ondblclick", 'copycode(' + index + ')');
            preItem.setAttribute("title", '雙擊復制');
        }
    }
 
    function copycode(i) {
        const range = document.createRange();
        range.selectNode(document.getElementsByTagName('pre')[i]);
        const selection = window.getSelection();
        if (selection.rangeCount > 0) selection.removeAllRanges();
        selection.addRange(range);
        document.execCommand('copy');
        Toast("復制成功",1500)
    }
 
    function Toast(msg, duration) {
        duration = isNaN(duration) ? 3000 : duration;
        var m = document.createElement('div');
        m.innerHTML = msg;
        m.style.cssText = "max-width:60%;min-width: 150px;padding:0 14px;height: 40px;color: rgb(255, 255, 255);line-height: 40px;text-align: center;border-radius: 4px;position: fixed;top: 50%;left: 50%;transform: translate(-50%, -50%);z-index: 999999;background: rgba(0, 0, 0,.7);font-size: 16px;";
        document.body.appendChild(m);
        setTimeout(function () {
            var d = 0.5;
            m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
            m.style.opacity = '0';
            setTimeout(function () {
                document.body.removeChild(m)
            }, d * 1000);
        }, duration);
    }
</script>
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容