跳到正文

科技·工程

洛谷美化样式

LotleTos_love_BIT约 54 分钟
原文

这是 2026年10月11日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年10月7日
收录
2026年10月11日
更新
2026年11月21日
篇幅
约 54 分钟

版本

  1. v3当前
  2. v2
  3. v1

众所周知,洛谷换了新前端后依旧不是很好看,于是我叫 deepseek 写了一个美化样式,耗费约 4040 元巨款。

效果

说明

这个只是修改前端,不可能导致封禁。

这个美化可能安装相对麻烦一点点,不过可自定义的程度高。

这个样式把洛谷原来长长的还需要滑动的侧栏分解成里两半放在左右两侧。

配合配套的篡改猴插件使用,可以在站内自定义背景图,切换卡片特效等,并且可以在站内一键切换亮色主题和暗色主题。 image.png

使用

首先你需要准备 Stylus 浏览器拓展,用于安装样式本体,再准备篡改猴拓展用于安装设置的脚本。

准备好 Stylus 后进入这个页面,找到这个按钮。

image.png

点击它后会跳转到这样的界面。 image.png 点击左上角的安装样式的按钮。回到洛谷后发现你的界面变了。

接下来打开篡改猴的安装新脚本页面。 image.png

把下面的代码复制进去。

code
C++
// ==UserScript==
// @name         洛谷主题 亮/暗 切换 + 站内设置
// @namespace    local.lotletos.luogu-theme-toggle
// @version      1.0.1791347014
// @description  洛谷主题的亮/暗切换按钮 + 站内设置面板(背景图、卡片/侧栏不透明度、过渡时长)
// @author       lotletos
// @match        https://*.luogu.com.cn/*
// @run-at       document-start
// @grant        GM_getValue
// @grant        GM_setValue
// @updateURL    http://127.0.0.1:8791/luogu-theme-toggle.user.js
// @downloadURL  http://127.0.0.1:8791/luogu-theme-toggle.user.js
// ==/UserScript==

/*
 * 和 Stylus 样式的关系
 * --------------------
 * 样式文件 luogu-dark.user.css 里:暗色是默认,亮色由 <html data-lg-theme="light"> 触发。
 * 本脚本负责三件事:
 *   ① 尽早写 data-lg-theme(document-start,避免刷新时先闪一下暗色)
 *   ② 顶栏插「暗 / 亮」切换按钮
 *   ③ 顶栏插「⚙」设置面板 —— 在站内就能调背景图和几个常用值
 *
 * 面板里的改动怎么写进去:
 *   全部通过【行内变量】写到 <html> 上(root.style.setProperty)。
 *   行内声明优先于任何作者样式表,所以能稳稳压过 Stylus 注入的 @var :root 块,
 *   也不会被主题里那些 !important(!important 只影响"声明之间"的优先级,
 *   行内普通声明本来就高于一切作者声明)。
 *
 * ⚠ 为什么必须【按模式分别存、切模式时重写一遍】:
 *   行内变量挂在 <html> 上,而 <html> 是两个模式共用的。
 *   如果只写一份,切到另一个模式它照样生效,就会把另一套配色也污染掉。
 *   所以:切模式时先把本脚本写过的行内变量全部清掉,再写入"该模式"的那一套。
 *
 * 为什么不用别的方案(都推演过):
 *   · Stylus 的 @var 做不到切换:它注入的只是 `:root { --名字: 值 }`,
 *     而 CSS 没有"按自定义属性的值分支"的能力,正文没法据此换整套调色板。
 *   · 整页 filter: invert() 不行:filter 会给 position:fixed 重建包含块,
 *     主题里顶栏/左侧栏/右侧胶囊全是 fixed,会跟着页面滚动跑掉。
 */

(function () {
  'use strict';

  // ── 防重复执行 ──
  // 篡改猴按「@namespace + @name」认脚本。如果改过 @name(本脚本就改过,
  // 从「洛谷主题 亮/暗 切换」改成加了「+ 站内设置」),篡改猴会以为是另一个脚本、
  // 装成【第二份】,旧的那份还在跑 —— 结果顶栏出现两个亮/暗按钮。
  // 这个全局标记能挡住"同一份脚本被注入两次",但挡不住"两份不同脚本共存",
  // 所以下面还有一段重复检测 + 提示用户去删。
  if (window.__lgThemeScriptLoaded) return;
  window.__lgThemeScriptLoaded = true;

  const KEY_THEME = 'lg-theme';       // 亮/暗
  const KEY_PREFS = 'lg-prefs';       // 面板里调的那些值
  const ATTR = 'data-lg-theme';
  const root = document.documentElement;

  // ── 偏好存哪儿:优先用篡改猴的【脚本存储】,localStorage 只当退路 ──
  // 为什么不能只用 localStorage:洛谷主站和它的子站是【不同源】,
  //   www / ti / help / class 各有一份互不相通的 localStorage。
  //   实测:在 www 上设好背景图,点侧栏的「洛谷有题」进 ti.luogu.com.cn,
  //   localStorage.getItem('lg-prefs') 是 null,data-lg-theme / data-lg-cardfx
  //   也全是空 —— 亮暗、背景图、卡片不透明度、卡片特效统统退回默认。
  //   而 Stylus 那份 usercss 用的是 domain("luogu.com.cn"),子站照样生效,
  //   于是就变成"样式在、设置不在"。
  // GM_getValue / GM_setValue 的存储是【按脚本】隔离、而不是按域名隔离的,
  // 同一份脚本 @match 到的所有站点共用一份,正好补上这个缺口。
  // ⚠ 所以文件头必须写 @grant GM_getValue / GM_setValue。
  //   写了 @grant 篡改猴会把脚本放进沙箱执行,本脚本只用到 document、
  //   定时器、MutationObserver、localStorage,沙箱里都有,不受影响。
  // 拿不到 GM_* 时(其他管理器、或被人改回 @grant none)自动退回 localStorage,
  // 行为等同于加这段之前 —— 只是设置仍按域名各存一份。
  const HAS_GM = typeof GM_getValue === 'function' && typeof GM_setValue === 'function';

  function storeGet(key) {
    if (HAS_GM) {
      try {
        const v = GM_getValue(key, null);
        if (v !== null && v !== undefined) return v;
      } catch (e) { /* 存储被禁用时继续往下走 */ }
    }
    try { return localStorage.getItem(key); } catch (e) { return null; }
  }

  function storeSet(key, value) {
    if (HAS_GM) { try { GM_setValue(key, value); } catch (e) {} }
    // 两边都写一份:读到 GM 那份就优先用 GM 的,读不到时才用这份。
    try { localStorage.setItem(key, value); } catch (e) {}
  }

  // 迁移:这个版本之前,设置只存在 localStorage 里(也就是只有 www 那一份)。
  // 如果不管它,用户升级完必须【随便动一下设置】才会把值推到 GM 存储里,
  // 在那之前点进 ti./help. 仍然是默认值 —— 看起来就像"没修好"。
  // 所以启动时补一次:GM 那份是空的、而本域名有一份旧的,就推上去。
  // ⚠ 只在 GM 为空时推,绝不反向覆盖 —— 否则在某个子站上开一次页面
  //   就会用那里的默认值把主站的设置冲掉。
  function migrateToGM() {
    if (!HAS_GM) return;
    for (const k of [KEY_THEME, KEY_PREFS]) {
      let gm = null;
      try { gm = GM_getValue(k, null); } catch (e) { continue; }
      if (gm !== null && gm !== undefined && gm !== '') continue;   // GM 已经有值,不动
      let ls = null;
      try { ls = localStorage.getItem(k); } catch (e) {}
      if (ls !== null && ls !== undefined && ls !== '') {
        try { GM_setValue(k, ls); } catch (e) {}
      }
    }
  }
  migrateToGM();

  // 面板底部显示的版本号 —— 用来一眼确认"更新到底装上没有"。
  // ⚠ 这里必须手动跟着改(服务端会把文件里的 @version 改写成 1.0.<mtime>
  //   好让篡改猴能识别更新,所以 @version 是给机器看的、这里这个才是给人看的)。
  //   每次改脚本记得一起 +1。
  const VERSION = '1.4.2';

  // 检测页面上是否已经存在同名按钮 —— 只有"两份脚本共存"时才会出现。
  // 这里不做自动清理(旧脚本自己的 MutationObserver 会把它再插回来,会打架),
  // 只明确告诉用户去篡改猴里删掉旧的那份。
  function detectDuplicates() {
    const n = document.querySelectorAll('[id="lg-theme-toggle"]').length;
    if (n > 1 && !sessionStorage.getItem('lg-dup-warned')) {
      try { sessionStorage.setItem('lg-dup-warned', '1'); } catch (e) {}
      console.warn('[洛谷主题] 检测到 ' + n + ' 个亮/暗按钮。'
        + '说明篡改猴里同时装着【新旧两份】本脚本,请删掉旧的那份(名字里没有「+ 站内设置」的那个)。');
      setTimeout(showDupNotice, 1500);
      return true;
    }
    return false;
  }

  function showDupNotice() {
    if (document.getElementById('lg-dup-notice')) return;
    const d = document.createElement('div');
    d.id = 'lg-dup-notice';
    d.setAttribute('style', [
      'position:fixed', 'z-index:2147483647', 'top:64px', 'left:50%',
      'transform:translateX(-50%)', 'max-width:min(560px,calc(100vw - 32px))',
      'box-sizing:border-box', 'padding:10px 14px', 'border-radius:10px',
      'background:#4a2b1a', 'color:#ffd9b8', 'border:1px solid #b3702f',
      'box-shadow:0 8px 24px rgba(0,0,0,.45)',
      'font:13px/1.6 system-ui,sans-serif',
    ].join(';'));
    d.innerHTML = '<b>顶栏出现了两个亮/暗按钮</b><br>'
      + '篡改猴里同时装着新旧两份本脚本,请打开篡改猴 → 删掉<b>旧的那份</b>'
      + '(名字里<b>没有</b>「+ 站内设置」的那个),然后刷新。'
      + '<span style="display:block;margin-top:6px;opacity:.8">点这里关闭 ×</span>';
    d.addEventListener('click', () => d.remove());
    document.body.appendChild(d);
    setTimeout(() => d.remove(), 20000);
  }

  // 面板能调的东西。每一行 = 一个 CSS 变量 + 一套控件描述。
  // perTheme=true 表示"按模式分别存"(暗色 / 亮色 各一份)。
  const FIELDS = [
    { key: 'bg',    css: '--lg-bg-image', kind: 'text',  perTheme: true,
      label: '页面背景图', hint: '只填网址就行(自动补 url("https://…"));填 none 去掉背景图' },
    { key: 'card',  css: '--lg-card-glass', kind: 'range', perTheme: true, color: true,
      label: '卡片底色不透明度', min: 0, max: 1, step: 0.02, fmt: v => v.toFixed(2) },
    { key: 'nav',   css: '--lg-nav', kind: 'range', perTheme: true, color: true,
      label: '侧栏不透明度', min: 0, max: 1, step: 0.02, fmt: v => v.toFixed(2) },
    { key: 'trans', css: '--lg-trans', kind: 'range', perTheme: false,
      label: '卡片过渡时长', min: 0.1, max: 1.5, step: 0.05, unit: 's', fmt: v => v.toFixed(2) + 's' },
    { key: 'noblur', kind: 'check', perTheme: false,
      label: '关闭毛玻璃模糊(省性能)',
      hint: '把卡片 / 顶栏 / 侧栏 / IDE 的磨砂关掉,改成纯色底。'
          + '模糊要实时采样背后的画面,是这套主题里最吃性能的一项。' },
    { key: 'cardfx', kind: 'select', perTheme: false,
      label: '卡片特效',
      options: [
        { v: '',      label: '默认(毛玻璃)' },
        { v: 'glass', label: '液态玻璃(高光 + 厚度)' },
      ],
      hint: '液态玻璃会叠四层高光做出厚度:左上镜面光斑 + 斜向渐亮 + 上下缘亮线 + 内发光,'
          + '悬停时卡片抬起 2px。做法参考 BigBallOfMud-Luogu。' },
  ];

  // 本脚本写过的行内变量名,切模式时要逐个清掉
  const MANAGED = FIELDS.filter(f => f.css).map(f => f.css);

  // ---------------------------------------------------------------- 状态

  let theme = 'dark';
  try {
    const saved = storeGet(KEY_THEME);
    if (saved === 'light' || saved === 'dark') theme = saved;
  } catch (e) { /* 隐私模式下存储可能不可用 */ }
  root.setAttribute(ATTR, theme);

  // prefs 结构:{ light: {bg:…, card:…}, dark: {…}, trans: … }
  let prefs = {};
  try { prefs = JSON.parse(storeGet(KEY_PREFS) || '{}') || {}; } catch (e) { prefs = {}; }

  function savePrefs() {
    try { storeSet(KEY_PREFS, JSON.stringify(prefs)); } catch (e) {}
  }

  function getPref(field) {
    if (field.perTheme) {
      const bucket = prefs[theme] || {};
      return bucket[field.key];
    }
    return prefs[field.key];
  }

  function setPref(field, value) {
    if (field.perTheme) {
      (prefs[theme] || (prefs[theme] = {}))[field.key] = value;
    } else {
      prefs[field.key] = value;
    }
    savePrefs();
  }

  // ---------------------------------------------------------------- 背景图兜底
  //
  // Stylus 的 @var 值是被【原样】塞进 background-image 的,
  // 而用户在设置面板里很容易敲出这两种有问题的写法:
  //   ① 完全裸的:          cdn.luogu.com.cn/a.webp        → 声明非法,整条被丢弃 → 纯色
  //   ② 有 url() 但缺协议: url("cdn.luogu.com.cn/a.webp") → 声明合法,但相对地址会拼到
  //      当前页面域名后面(→ www.luogu.com.cn/…/cdn.luogu.com.cn/…),
  //      洛谷对未知路径返回 200 + text/html,浏览器解不出图 → 还是纯色,且看 CSS 完全看不出问题
  // 所以这里统一补成 url("https://…")。填面板的值也走同一个函数。

  function normalizeBg(v) {
    if (!v) return null;
    v = String(v).trim();
    if (!v) return null;
    if (/^(none|inherit|initial|unset|revert)$/i.test(v)) return v;   // 合法,原样用
    if (/^(repeating-)?(linear|radial|conic)-gradient\(/i.test(v)) return v;
    if (/^(image-set|cross-fade|element|paint)\(/i.test(v)) return v;
    if (/^var\(/i.test(v)) return null;               // 只是个别名,不去动它

    const m = /^url\(\s*(['"]?)([\s\S]*?)\1\s*\)$/i.exec(v);
    const inner = (m ? m[2] : v).trim();
    if (!inner) return null;
    // 已经是绝对地址 / 内联数据 / 根路径 / 锚点 → 不动
    if (/^(data:|blob:|[a-z][a-z0-9+.-]*:\/\/|\/\/|\/|#)/i.test(inner)) return m ? null : `url("${inner}")`;
    return 'url("https://' + inner.replace(/"/g, '') + '")';
  }

  // ---------------------------------------------------------------- 颜色 alpha 工具
  //
  // ⚠ 这里踩过一个坑:--lg-card-glass / --lg-nav 这两个变量装的是【颜色】
  //   (比如 rgba(255,255,255,0.06)),不是数字。
  //   滑块如果直接把 0.46 写进去,变量就成了 `0.46` —— 非法颜色,
  //   卡片底色会被整个丢掉(变成透明,比原来还糟),而且不报错。
  //   所以这两个滑块必须"读出当前 RGB,只换 alpha"。

  function parseColor(v) {
    const m = /rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*(?:,\s*([\d.]+)\s*)?\)/i.exec(v || '');
    if (!m) return null;
    return { r: +m[1], g: +m[2], b: +m[3], a: m[4] === undefined ? 1 : +m[4] };
  }

  function withAlpha(rgb, a) {
    return `rgba(${Math.round(rgb.r)}, ${Math.round(rgb.g)}, ${Math.round(rgb.b)}, ${a})`;
  }

  // 取某个变量"当前实际生效"的 RGB,作为滑块改 alpha 的基准
  function currentRgb(cssVar) {
    return parseColor(getComputedStyle(root).getPropertyValue(cssVar)) || { r: 128, g: 128, b: 128, a: 1 };
  }

  // ---------------------------------------------------------------- 关模糊
  //
  // 实现:给 <html> 挂 data-lg-noblur,配一条 <style> 把 backdrop-filter 打掉。
  //
  // ⚠ 必须用 @layer,不能靠堆特异性:
  //   主题里给卡片加模糊的是
  //     .l-card.l-card:not(:has(.ide-container)) { backdrop-filter: … !important }
  //   特异性 (0,3,0) 且带 !important;hover 那条 `#app .l-card.l-card:hover`
  //   更是 (1,2,0)。想用选择器压过它们,得往选择器里塞 id、重复属性名,
  //   又脏又容易漏(实测第一版就没压住卡片,只把 blur 变成了 blur(0px))。
  //
  //   CSS 层叠规则里有一条反直觉但正好救命的约定:
  //     · 普通声明:     未分层的 赢过 分层的
  //     · !important 声明:分层的 反而 赢过 未分层的
  //   所以在 @layer 里写 !important,可以【无视特异性】压过整张样式表里
  //   所有未分层的 !important。这才是干这事的正确工具。
  //
  // 为什么不用 `*` 通吃:那会让引擎给【每个元素】都算一遍 backdrop-filter,
  // 而本来只有几十个元素有这属性 —— 这开关就是为省性能,自己不能先费掉。
  //
  // 另外 apply() 里还会把 --lg-card-blur / --lg-ide-blur 设成 0px:
  // 让变量驱动的那批从源头就不产生模糊,双保险。
  const NOBLUR_CSS = `
@layer lg-noblur {
  html[data-lg-noblur] :is(
    .l-card, .card, .lg-article, .top-bar, .navbar, .user-nav, .user-header-bottom,
    .nav-group, .panel, .theme-page, .am-comment-main, .reply-item, .header-layout,
    .exlg-window, .exlg-dialog-container, .exlg-dialog-btn, .ide-container
  ),
  html[data-lg-noblur] nav,
  html[data-lg-noblur] header,
  html[data-lg-noblur] footer {
    -webkit-backdrop-filter: none !important;
    backdrop-filter: none !important;
  }
}`;

  function ensureNoblurStyle() {
    if (document.getElementById('lg-noblur-style')) return;
    const s = document.createElement('style');
    s.id = 'lg-noblur-style';
    s.textContent = NOBLUR_CSS;
    (document.head || document.documentElement).appendChild(s);
  }

  // ---------------------------------------------------------------- 应用

  function apply() {
    // ① 先清掉上一轮写过的(<html> 是两个模式共用的,不清会串)
    MANAGED.forEach(k => root.style.removeProperty(k));

    // ①b 关模糊开关:不在 FIELDS 的变量循环里,因为它改的是属性不是变量
    if (prefs.noblur) {
      ensureNoblurStyle();
      root.setAttribute('data-lg-noblur', '');
      root.style.setProperty('--lg-card-blur', '0px');
      root.style.setProperty('--lg-ide-blur', '0px');
    } else {
      root.removeAttribute('data-lg-noblur');
      // ⚠ 关闭时要把上面写过的行内值清掉,否则会残留 blur(0px),
      //   看不出区别但确实没恢复成用户在 Stylus 里设的模糊强度
      root.style.removeProperty('--lg-card-blur');
      root.style.removeProperty('--lg-ide-blur');
    }

    // ①c 卡片特效:同样改的是 <html> 上的属性,不进变量循环
    if (prefs.cardfx) root.setAttribute('data-lg-cardfx', prefs.cardfx);
    else root.removeAttribute('data-lg-cardfx');

    // ② 写入当前模式该有的值
    for (const f of FIELDS) {
      if (!f.css) continue;
      let v = getPref(f);
      if (v === undefined || v === null || v === '') continue;

      if (f.kind === 'text') {
        const norm = normalizeBg(v);
        if (norm === null) continue;
        root.style.setProperty(f.css, norm);
      } else {
        const n = Number(v);
        if (!isFinite(n)) continue;
        if (f.color) {
          // 注意:本函数第 ① 步已经把行内值清掉了,所以这里读到的是
          // 【该模式自身的】基准色(暗色偏蓝黑、亮色纯白),不会被上一轮覆盖污染
          root.style.setProperty(f.css, withAlpha(currentRgb(f.css), n));
        } else {
          root.style.setProperty(f.css, f.unit ? n + f.unit : String(n));
        }
      }
    }

    // ③ 兜底:Stylus 里那两个 @var 如果填了裸网址/缺协议,也顺手修掉
    //    (只在没被面板覆盖时才有意义,所以放在最后)
    fixStylusBgVars();
  }

  function fixStylusBgVars() {
    const cs = getComputedStyle(root);
    for (const k of ['--lg-bg-image', '--lg-bg-image-light']) {
      if (root.style.getPropertyValue(k)) continue;     // 面板已经给过值了
      const raw = (cs.getPropertyValue(k) || '').trim();
      if (!raw || /^(url\(|none$)/i.test(raw)) continue;
      if (/^(repeating-)?(linear|radial|conic)-gradient\(/i.test(raw)) continue;
      if (/^var\(/i.test(raw)) continue;
      const norm = normalizeBg(raw);
      if (norm) root.style.setProperty(k, norm);
    }
  }

  // ---------------------------------------------------------------- 顶栏按钮

  let btn = null, gear = null, panel = null;

  function pillButton(id, text, title) {
    const b = document.createElement('a');
    b.id = id;
    b.href = 'javascript:void 0';
    b.title = title;
    b.textContent = text;
    b.setAttribute('role', 'button');
    b.setAttribute('style', [
      'display:inline-flex', 'align-items:center', 'justify-content:center',
      'min-width:26px', 'height:26px', 'padding:0 7px', 'margin:0 6px',
      'cursor:pointer', 'border-radius:13px', 'font-size:13px', 'line-height:1',
      'font-family:inherit', 'text-decoration:none', 'user-select:none', 'flex:0 0 auto',
      'transition:background .15s ease',
    ].join(';'));
    b.addEventListener('mouseenter', function () {
      b.style.background = theme === 'light' ? 'rgba(0,0,0,.08)' : 'rgba(255,255,255,.14)';
    });
    b.addEventListener('mouseleave', function () { b.style.background = 'transparent'; });
    return b;
  }

  function syncButtons() {
    const light = theme === 'light';
    const fg = light ? '#333' : '#ddd';
    const bd = light ? '1px solid rgba(0,0,0,.18)' : '1px solid rgba(255,255,255,.22)';
    for (const b of [btn, gear]) {
      if (!b) continue;
      b.style.color = fg;
      b.style.border = bd;
    }
    if (btn) {
      btn.textContent = light ? '亮' : '暗';
      btn.title = light ? '当前:亮色模式(点击切到暗色)' : '当前:暗色模式(点击切到亮色)';
    }
    if (gear) gear.title = '主题设置(背景图 / 不透明度 / 过渡)';
  }

  function setTheme(next) {
    theme = next;
    root.setAttribute(ATTR, next);
    try { storeSet(KEY_THEME, next); } catch (e) {}
    apply();          // 先把该模式的值写上,再刷新 UI(控件要显示当前模式的值)
    syncButtons();
    syncPanel();
  }

  // ---------------------------------------------------------------- 设置面板

  function panelStyle() {
    return [
      'position:fixed', 'z-index:2147483646', 'top:64px', 'right:16px',
      'width:320px', 'max-width:calc(100vw - 32px)', 'box-sizing:border-box',
      // 面板越加越长,小屏上会被视口截掉 —— 限高 + 自己滚
      'max-height:calc(100vh - 84px)', 'overflow-y:auto', 'overscroll-behavior:contain',
      'padding:14px 16px', 'border-radius:14px',
      'background:var(--lg-solid, #16181c)', 'color:var(--lg-text, #e6e9ef)',
      'border:1px solid rgba(128,128,128,.35)',
      'box-shadow:0 8px 28px rgba(0,0,0,.45)',
      'font:13px/1.6 system-ui,-apple-system,"Segoe UI",sans-serif',
      'display:none',
    ].join(';');
  }

  function buildPanel() {
    const box = document.createElement('div');
    box.id = 'lg-theme-panel';
    box.setAttribute('style', panelStyle());

    const title = document.createElement('div');
    title.setAttribute('style', 'display:flex;align-items:center;justify-content:space-between;margin-bottom:10px;font-weight:700');
    title.innerHTML = '<span>主题设置</span>';
    const close = document.createElement('a');
    close.href = 'javascript:void 0';
    close.textContent = '✕';
    close.setAttribute('style', 'cursor:pointer;opacity:.7;padding:0 2px');
    close.addEventListener('click', () => togglePanel(false));
    title.appendChild(close);
    box.appendChild(title);

    const note = document.createElement('div');
    note.setAttribute('style', 'opacity:.7;margin-bottom:12px;font-size:12px');
    note.textContent = '下面这些按「当前模式」分别保存;切模式后会显示另一套值。';
    box.appendChild(note);

    for (const f of FIELDS) {
      // 勾选框单独一套结构:不进下面「左标签 + 右数值」的模板,
      // 否则会被 space-between 撑开(勾选框跑到最左、文字飞到最右)。
      if (f.kind === 'check') {
        const wrap = document.createElement('label');
        wrap.setAttribute('style',
          'display:flex;align-items:center;gap:8px;margin-bottom:12px;cursor:pointer');
        const box_ = document.createElement('input');
        box_.type = 'checkbox';
        box_.setAttribute('style',
          'width:16px;height:16px;accent-color:#4c8bf5;cursor:pointer;flex:0 0 auto;margin:0');
        const txt = document.createElement('span');
        txt.textContent = f.label;
        wrap.appendChild(box_);
        wrap.appendChild(txt);
        box_.addEventListener('change', function () {
          setPref(f, box_.checked);
          apply(); syncPanel();
        });
        box.appendChild(wrap);
        if (f.hint) {
          const h = document.createElement('div');
          h.setAttribute('style', 'opacity:.6;font-size:11px;margin:-8px 0 12px 0');
          h.textContent = f.hint;
          box.appendChild(h);
        }
        f._input = box_;
        f._val = null;      // 勾选框没有"右侧数值",别把标签元素当 _val,
                            // 否则 syncPanel 里那句 _val.textContent='' 会把标签抹掉
        continue;
      }

      const row = document.createElement('div');
      row.setAttribute('style', 'margin-bottom:12px');

      const head = document.createElement('div');
      head.setAttribute('style', 'display:flex;justify-content:space-between;align-items:baseline;margin-bottom:4px');
      const lab = document.createElement('span');
      lab.textContent = f.label;
      const val = document.createElement('span');
      val.setAttribute('style', 'opacity:.75;font-size:12px;font-variant-numeric:tabular-nums');
      head.appendChild(lab); head.appendChild(val);
      row.appendChild(head);

      let input;
      if (f.kind === 'select') {
        input = document.createElement('select');
        input.setAttribute('style', [
          'width:100%', 'box-sizing:border-box', 'padding:6px 8px',
          'border-radius:8px', 'border:1px solid rgba(128,128,128,.45)',
          'background:rgba(128,128,128,.14)', 'color:inherit', 'font:12px/1.5 inherit',
        ].join(';'));
        (f.options || []).forEach(function (o) {
          const op = document.createElement('option');
          op.value = o.v;
          op.textContent = o.label;
          // 下拉展开时用的是系统原生弹层,得单独给它上色,否则在暗色下是白底
          op.setAttribute('style', 'background:var(--lg-solid, #16181c);color:var(--lg-text, #e6e9ef)');
          input.appendChild(op);
        });
        input.addEventListener('change', function () {
          setPref(f, input.value);
          apply(); syncPanel();
        });
      } else if (f.kind === 'text') {
        input = document.createElement('input');
        input.type = 'text';
        input.placeholder = 'https://… 或留空';
        input.setAttribute('style', [
          'width:100%', 'box-sizing:border-box', 'padding:6px 8px',
          'border-radius:8px', 'border:1px solid rgba(128,128,128,.45)',
          'background:rgba(128,128,128,.14)', 'color:inherit',
          'font:12px/1.4 ui-monospace,monospace',
        ].join(';'));
        input.addEventListener('change', function () {
          const norm = normalizeBg(input.value);
          if (input.value.trim() && norm === null) return;    // 无效输入不落库
          setPref(f, input.value.trim());
          input.value = norm && norm !== 'none' ? input.value.trim() : input.value.trim();
          apply(); syncPanel();
        });
      } else {
        input = document.createElement('input');
        input.type = 'range';
        input.min = f.min; input.max = f.max; input.step = f.step;
        input.setAttribute('style', 'width:100%;accent-color:#4c8bf5');
        input.addEventListener('input', function () {
          setPref(f, Number(input.value));
          apply(); syncPanel();
        });
      }
      if (f.kind !== 'check') row.appendChild(input);   // 勾选框已经插在标签那一行了

      if (f.hint) {
        const h = document.createElement('div');
        h.setAttribute('style', 'opacity:.6;font-size:11px;margin-top:4px');
        h.textContent = f.hint;
        row.appendChild(h);
      }

      f._input = input; f._val = val;
      box.appendChild(row);
    }

    // 版本号:一眼确认"更新装上没有"
    const ver = document.createElement('div');
    ver.setAttribute('style',
      'margin-top:10px;padding-top:8px;border-top:1px solid rgba(128,128,128,.25);'
      + 'opacity:.55;font-size:11px;display:flex;justify-content:space-between');
    ver.innerHTML = '<span>脚本 v' + VERSION + '</span>'
      + '<span>样式版本看 Stylus 里那份</span>';
    box.appendChild(ver);

    // 底部:恢复默认 / 关闭
    const foot = document.createElement('div');
    foot.setAttribute('style', 'display:flex;justify-content:space-between;margin-top:10px;padding-top:10px;border-top:1px solid rgba(128,128,128,.25)');
    const reset = document.createElement('a');
    reset.href = 'javascript:void 0';
    reset.textContent = '恢复本模式默认';
    reset.setAttribute('style', 'cursor:pointer;color:#4c8bf5');
    reset.addEventListener('click', function () {
      if (window.confirm('恢复当前模式的默认设置?(清掉本模式的覆盖值)')) {
        if (prefs[theme]) delete prefs[theme];
        savePrefs(); apply(); syncPanel();
      }
    });
    const closeAll = document.createElement('a');
    closeAll.href = 'javascript:void 0';
    closeAll.textContent = '关闭';
    closeAll.setAttribute('style', 'cursor:pointer;opacity:.8');
    closeAll.addEventListener('click', () => togglePanel(false));
    foot.appendChild(reset); foot.appendChild(closeAll);
    box.appendChild(foot);

    return box;
  }

  function syncPanel() {
    if (!panel) return;
    for (const f of FIELDS) {
      const v = getPref(f);
      if (f.kind === 'check') {
        f._input.checked = !!v;
      } else if (f.kind === 'select') {
        f._input.value = v || '';
        if (f._val) f._val.textContent = '';
      } else if (f.kind === 'text') {
        f._input.value = (v === undefined || v === null) ? '' : String(v);
        f._val.textContent = (v === undefined || v === null || v === '') ? '(用 Stylus 的值)' : '';
      } else {
        // 没设过就显示当前实际生效的值,让滑块不空着
        let cur = v;
        if (cur === undefined || cur === null) {
          const cs = getComputedStyle(root).getPropertyValue(f.css).trim();
          if (f.color) {
            const c = parseColor(cs);
            cur = c ? c.a : 1;          // 颜色类:滑块代表 alpha
          } else {
            cur = parseFloat(cs);
          }
          if (!isFinite(cur)) cur = f.min;
        }
        f._input.value = cur;
        f._val.textContent = (f.fmt ? f.fmt(Number(cur)) : cur) + (v === undefined || v === null ? '(默认)' : '');
      }
    }
  }

  function togglePanel(show) {
    if (!panel) { panel = buildPanel(); document.body.appendChild(panel); }
    const want = (show === undefined) ? (panel.style.display === 'none') : show;
    panel.style.display = want ? 'block' : 'none';
    if (want) syncPanel();
  }

  const HOSTS = [
    '.top-bar .user-nav',
    '.top-bar .right',
    '.top-bar .nav-search',
    'header .user-nav',
    '.user-nav.rside',
    '.user-nav',
    '.navbar__items--right',
    'nav.navbar .navbar__inner',
    '.top-bar',
  ];

  function tryInject() {
    if (btn && btn.isConnected && gear && gear.isConnected) return true;
    let host = null;
    for (const sel of HOSTS) {
      const el = document.querySelector(sel);
      if (el && el.offsetParent !== null) { host = el; break; }
    }
    if (!host) return false;

    if (!btn) {
      btn = pillButton('lg-theme-toggle', '暗', '切换 亮色 / 暗色 主题');
      btn.addEventListener('click', function (ev) {
        ev.preventDefault(); ev.stopPropagation();
        setTheme(theme === 'light' ? 'dark' : 'light');
      });
    }
    if (!gear) {
      gear = pillButton('lg-theme-gear', '⚙', '主题设置');
      gear.addEventListener('click', function (ev) {
        ev.preventDefault(); ev.stopPropagation();
        togglePanel();
      });
    }
    syncButtons();
    host.insertBefore(gear, host.firstChild);
    host.insertBefore(btn, host.firstChild);
    return true;
  }

  let timer = null;
  const mo = new MutationObserver(function () {
    if (timer) return;
    timer = setTimeout(function () { timer = null; tryInject(); }, 300);
  });

  function boot() {
    apply();
    tryInject();
    detectDuplicates();
    mo.observe(document.documentElement, { childList: true, subtree: true });
    let n = 0;
    const iv = setInterval(function () {
      apply();
      if (tryInject() || ++n > 20) clearInterval(iv);
    }, 500);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', boot);
  } else {
    boot();
  }
})();

点击保存后回到洛谷界面,刷新,顶栏会出现这两个按钮。左边按钮是切换暗色和亮色的,右边是设置。

点击右边这个齿轮,进入设置菜单,然后你就可以设置背景图片等东西了(背景图片用图床链接)注意亮色和暗色模式的设置是独立的。

image.png

卡片的模糊每帧都要计算,如果你的设备过于低配,觉得卡的话可以在设置菜单关掉模糊。