跳到正文

剪贴板

剪贴板 oscrv8ja

原文
剪贴板信息

剪贴板信息

收录
更新

代码语言标签 插件源码。

JavaScript
// ==UserScript==
// @name         代码语言标签
// @namespace    http://tampermonkey.net/
// @version      3.3
// @description  在代码块上方显示语言标签
// @author       Forever_Rain
// @match        https://www.luogu.com.cn/discuss/*
// @match        https://www.luogu.com/article/*
// @match        https://www.luogu.com.cn/article/*
// @match        https://www.luogu.com/discuss/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    const MATCH = {
        'cpp': 'C++',
        'python': 'Python',
        'c': 'C',
        'javascript': 'Javascript',
        'markdown': 'Markdown',
        'latex': 'Latex'
    };
    function addLabels() {
        const codes = document.querySelectorAll('code[class*="language-"]');
        codes.forEach(code => {
            if (code.dataset.langLabeled === 'true') return;
            const classList = code.className.split(/\s+/);
            let lang = '';
            for (const cls of classList) {
                if (cls.startsWith('language-')) {
                    lang = cls.replace('language-', '');
                    break;
                }
            }
            if (!lang) return;
            const displayName = MATCH[lang] || lang;
            let pre = code.parentElement;
            while (pre && pre.tagName !== 'PRE') {
                pre = pre.parentElement;
            }
            if (!pre) return;
            const label = document.createElement('div');
            label.textContent = displayName;
            label.style.cssText = `
                display: block;
                width: 100%;
                box-sizing: border-box;
                background: #cad5e8;   // 背景色
                color: #000000;        // 文字颜色
                font-family: 'Segoe UI', 'Helvetica Neue', Arial, sans-serif;
                font-size: 13px;
                font-weight: 700;
                padding: 5px 16px;
                margin: 0;
                letter-spacing: 0.6px;
                text-transform: uppercase;
                border-radius: 4px 4px 0 0;
            `;
            pre.parentNode.insertBefore(label, pre);
            code.dataset.langLabeled = 'true';
        });
    }
    addLabels();
    const observer = new MutationObserver(() => {
        addLabels();
    });
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
})();