跳到正文

闲话

洛谷美化油猴插件

DanseSolo约 25 分钟
原文

这是 2026年4月25日 存档的第 2 版,不是当前版本。查看当前版本

文章信息与版本

隐藏题号 & 难度。

代码
// ==UserScript==
// @name         Luogu 题号+难度 整合工具
// @namespace    http://tampermonkey.net/
// @version      1.2
// @description  题号切换+难度隐藏 整合版,主页面隐藏难度按钮,题库页不干扰
// @author       LTTXiaochuan
// @match        https://www.luogu.com.cn/*
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_registerMenuCommand
// @run-at       document-idle
// ==/UserScript==

(function() {
    'use strict';

    // ====================== 工具函数:页面判断 ======================
    const path = location.pathname;
    const searchParams = new URLSearchParams(location.search);

    // 1. 仅匹配:/problem/Pxxxx 或 /contest/xxx/problem/xxx,排除 /problem/list 等题库页
    const isProblemDetailPage =
        (path.startsWith('/problem/') && !path.includes('/list')) ||
        (path.includes('/contest/') && path.includes('/problem/'));

    // 2. 判断是否为洛谷主页面(根路径 / 或 /?xxx)
    const isHomePage = path === '/' && searchParams.get('pid') === null;

    // ====================== 第一部分:题号切换功能(仅题目详情页执行) ======================
    if (isProblemDetailPage) {
        // 默认隐藏
        let mode = GM_getValue('pid_mode', 'hidden');

        // 核心样式
        const css1 = `
        #pidBtn {
            position: fixed;
            top: 12px;
            right: 12px;
            z-index: 999999;
            background: rgba(0,0,0,0.6);
            color: #fff !important;
            padding: 6px 8px;
            font-size: 12px;
            border-radius: 6px;
            cursor: move;
            user-select: none;
            box-shadow: 0 2px 6px rgba(0,0,0,.4);
            min-width: 120px;
            text-align: center;
            font-family: 'Segoe UI',微软雅黑,sans-serif;
        }
        #pidBtn small { opacity: .8; display:block; font-size:11px; margin-top:2px; color: #fff !important; }
        /* 隐藏题号 */
        body.hidePid .breadcrumb a[href*="P"] { display:none !important; }
        /* 打印只隐藏按钮,不破坏页面 */
        @media print { #pidBtn { display:none !important; } }
        `;
        const style1 = document.createElement('style');
        style1.textContent = css1;
        document.head.appendChild(style1);

        // 执行功能 + 侧栏暴力隐藏
        function run() {
            document.body.classList.toggle('hidePid', mode === 'hidden');

            if(mode === 'hidden'){
                const all = document.getElementsByTagName('*');
                for(let el of all){
                    if(el.textContent.trim() === '题目编号'){
                        const val = el.nextElementSibling || el.parentElement.lastElementChild;
                        if(val && val.textContent.startsWith('P')) val.style.display = 'none';
                    }
                }
            }else{
                const all = document.getElementsByTagName('*');
                for(let el of all){
                    if(el.textContent.trim() === '题目编号'){
                        const val = el.nextElementSibling || el.parentElement.lastElementChild;
                        if(val) val.style.display = '';
                    }
                }
            }

            // 主标题原版逻辑
            const h1 = document.querySelector('h1');
            if(h1){
                if(mode === 'hidden'){ h1._o = h1._o || h1.textContent; h1.textContent = 'LoveFurina'; }
                else { h1._o && (h1.textContent = h1._o); }
            }
            // 文字修改为:隐藏题号/显示题号 + (点击切换)
            const label = mode === 'hidden' ? '隐藏题号' : '显示题号';
            document.getElementById('pidBtn').innerHTML = `<strong>${label}</strong><small>(点击切换)</small>`;
        }

        // 创建按钮
        function btn() {
            const b = document.createElement('div');
            b.id = 'pidBtn';
            const x=GM_getValue('x'), y=GM_getValue('y');
            if(x!=null&&y!=null){
                b.style.left=x+'px';
                b.style.top=y+'px';
                b.style.right='auto';
            }else{
                b.style.bottom = "65px";
                b.style.right = "12px";
                b.style.top = "auto";
            }

            let ox,oy,d=false;
            let isDragged = false;

            b.onmousedown = (e)=>{
                d=true;
                isDragged = false;
                ox=e.clientX-b.offsetLeft;
                oy=e.clientY-b.offsetTop;
                b.style.opacity=0.6;
            };

            document.onmousemove = (e)=>{
                if(!d)return;
                isDragged = true;
                b.style.left=Math.max(0,Math.min(innerWidth-b.offsetWidth,e.clientX-ox))+'px';
                b.style.top=Math.max(0,Math.min(innerHeight-b.offsetHeight,e.clientY-oy))+'px';
            };

            document.onmouseup = ()=>{
                if(!d)return;
                d=false;
                b.style.opacity=1;
                GM_setValue('x',b.offsetLeft);
                GM_setValue('y',b.offsetTop);
            };

            b.onclick = ()=>{
                if(!isDragged){
                    mode=mode==='hidden'?'show':'hidden';
                    GM_setValue('pid_mode',mode);
                    run();
                }
            };

            document.body.appendChild(b);
            run();
        }

        // 标签页标题(仅题目页执行)
        const targetTitle = "芙芙超可爱~";
        function setFurinaTitle() {
            if (document.title !== targetTitle) {
                document.title = targetTitle;
            }
        }
        setInterval(setFurinaTitle, 300);

        // 极速响应:轮询间隔50ms(仅题目页执行)
        setInterval(() => {
            const h1 = document.querySelector('h1');
            if(h1){
                if(mode === 'hidden'){
                    h1._o = h1._o || h1.textContent;
                    h1.textContent = 'LoveFurina';
                } else {
                    h1._o && (h1.textContent = h1._o);
                }
            }
        }, 50);

        // 极速响应:题号隐藏(仅题目页执行)
        setInterval(() => {
            if(mode === 'hidden'){
                const all = document.getElementsByTagName('*');
                for(let el of all){
                    if(el.textContent.trim() === '题目编号'){
                        const val = el.nextElementSibling || el.parentElement.lastElementChild;
                        if(val && val.textContent.startsWith('P')) val.style.display = 'none';
                    }
                }
            }
        }, 50);

        // 启动题号功能(仅题目页执行)
        window.addEventListener('load', ()=>{ btn(); setTimeout(run,300); setTimeout(run,800); });
    }

    // ====================== 第二部分:难度隐藏功能(主页面除外,完全不变) ======================
    if (!isHomePage) { // 主页面不执行难度功能
        const DEFAULT_MODE = GM_getValue('lg_diff_mode', 'hover');
        const selectors = [
            '.l-flex-info-row a[href*="problem/list?difficulty"] span',
            '.difficulty span span',
            '.difficulty span.lfe-caption'
        ];

        const styleId = 'tm-luogu-diff-style';
        const css2 = `
        .tm-diff-hidden, .tm-diff-hover { transition: opacity .15s ease !important; }
        .tm-diff-hidden { opacity: 0 !important; }
        .tm-diff-hover { opacity: 0 !important; }
        .tm-diff-hover:hover { opacity: 1 !important; }
        #tm-luogu-diff-toggle {
            position: fixed;
            bottom: 12px;
            right: 12px;
            z-index: 999999;
            background: rgba(0,0,0,0.6);
            color: #fff !important;
            padding: 6px 8px;
            font-size: 12px;
            border-radius: 6px;
            cursor: move;
            user-select: none;
            box-shadow: 0 2px 6px rgba(0,0,0,.4);
        }
        #tm-luogu-diff-toggle small { opacity: .8; display:block; font-size:11px; margin-top:2px; color: #fff !important; }
        `;

        function injectStyle() {
            if (document.getElementById(styleId)) return;
            const s = document.createElement('style');
            s.id = styleId;
            s.textContent = css2;
            document.head.appendChild(s);
        }

        let currentMode = DEFAULT_MODE;
        function applyToElement(el, mode) {
            el.classList.remove('tm-diff-hidden', 'tm-diff-hover');
            if (mode === 'hidden') el.classList.add('tm-diff-hidden');
            else if (mode === 'hover') el.classList.add('tm-diff-hover');
        }

        function applyModeToAll(mode) {
            const combined = selectors.join(',');
            document.querySelectorAll(combined).forEach(el => applyToElement(el, mode));
        }

        let mo = null;
        function startObserver() {
            if (mo) return;
            mo = new MutationObserver(muts => {
                if (muts.some(m => m.addedNodes && m.addedNodes.length)) {
                    applyModeToAll(currentMode);
                }
            });
            mo.observe(document.body, { childList: true, subtree: true });
        }

        function saveMode(mode) {
            currentMode = mode;
            GM_setValue('lg_diff_mode', mode);
            updateToggleText();
            applyModeToAll(mode);
        }

        function nextMode(m) {
            if (m === 'show') return 'hover';
            if (m === 'hover') return 'hidden';
            return 'show';
        }

        function createToggle() {
            if (document.getElementById('tm-luogu-diff-toggle')) return;
            const btn = document.createElement('div');
            btn.id = 'tm-luogu-diff-toggle';
            btn.title = '点击切换难度显示模式';
            btn.style.minWidth = '120px';
            btn.style.textAlign = 'center';
            btn.style.fontFamily = 'Segoe UI,微软雅黑,sans-serif';

            const savedX = GM_getValue('lg_diff_x', null);
            const savedY = GM_getValue('lg_diff_y', null);
            if (savedX !== null && savedY !== null) {
                btn.style.left = savedX + 'px';
                btn.style.top = savedY + 'px';
                btn.style.right = 'auto';
            }

            btn.addEventListener('click', (e) => {
                if (btn._dragging) return;
                saveMode(nextMode(currentMode));
            });

            makeDraggable(btn);
            document.body.appendChild(btn);
            updateToggleText();
        }

        function updateToggleText() {
            const btn = document.getElementById('tm-luogu-diff-toggle');
            if (!btn) return;
            const label = (currentMode === 'show') ? '显示难度' : (currentMode === 'hover') ? '悬停显示难度' : '隐藏难度';
            btn.innerHTML = ` <strong> ${label} </strong> <small> (点击切换) </small> `;
        }

        // 拖动逻辑
        function makeDraggable(el) {
            let offsetX, offsetY, isDown = false;

            el.addEventListener('mousedown', (e) => {
                isDown = true;
                el._dragging = false;
                offsetX = e.clientX - el.offsetLeft;
                offsetY = e.clientY - el.offsetTop;
                el.style.opacity = "0.6";
                document.addEventListener('mousemove', move);
                document.addEventListener('mouseup', up);
            });

            function move(e) {
                if (!isDown) return;
                el._dragging = true;
                let newLeft = e.clientX - offsetX;
                let newTop = e.clientY - offsetY;

                const maxLeft = window.innerWidth - el.offsetWidth;
                const maxTop = window.innerHeight - el.offsetHeight;
                newLeft = Math.max(0, Math.min(maxLeft, newLeft));
                newTop = Math.max(0, Math.min(maxTop, newTop));

                el.style.left = newLeft + 'px';
                el.style.top = newTop + 'px';
                el.style.right = 'auto';
            }

            function up() {
                if (!isDown) return;
                isDown = false;
                el.style.opacity = "1";
                document.removeEventListener('mousemove', move);
                document.removeEventListener('mouseup', up);
                GM_setValue('lg_diff_x', el.offsetLeft);
                GM_setValue('lg_diff_y', el.offsetTop);
                setTimeout(() => { el._dragging = false; }, 50);
            }
        }

        function init() {
            injectStyle();
            createToggle();
            applyModeToAll(currentMode);
            startObserver();
            window.addEventListener('load', () => setTimeout(() => applyModeToAll(currentMode), 300));
        }

        // 启动难度功能
        init();
    }
})();