正文
增加 1361 行删除 1174 行
123456 行未改动1213141516171819202 行未改动2324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323效果展示(deepseek/atcoder/QQ浏览器-新标签页/洛谷部分页面)6 行未改动首先,本脚本肯定使用了deepseek。无论是学习这个语言还是后期更改。并且似乎和洛谷不太适配。(但是后面作者发现只要自己新建一个主题然后去掉洛谷自带的背景就可以正常用了。——2026.8.3 21:32:50)[洛谷专用——他人](https://www.luogu.com.cn/article/k0wlh572)如何使用---- 很显然,你需要一个tempermonkey。不过似乎有人不知道。首先,点开右上角菜单,找到“扩展”/“插件”,然后点进去,找到“获取拓展”。然后搜索tempermonkey,下载。接着新建脚本,Ctrl+S保存。它就自动启动了。- 启动脚本后刷新网页。然后点击右下角的🎨按钮,点击图片/视频,就可以添加了。如果看不到图,就调一下层级,因为不同网站它文字的层级不同。甚至有的网站它文字框(有的甚至没有文字框)是和背景同一层级的,所以说,您的图片只能置顶了(调一下透明度就好啦)。小问题-----2 行未改动目前已知问题网站 [QQ邮箱](mail.qq.com)更新预告------ 更丝滑的背景转换。- 切换背景时的某些问题。- 按钮的修复。更新日志----- 2026.2.26 OK,现在可以在洛谷上用了。但是bug好多(不太适配),还是建议找单独适用洛谷的脚本。如果硬要用这个,在黑名单里剔除就好。——已修。现在完全可以适配。- 2026.2.27 将视频限制上调为25MB,支持定时更换背景。- 2026.9.24 可以拖动的按钮,但是似乎有点问题???- 2026.10.11 可以直接从一些网站的图床上传图片。不用再下载到本地。但是这会使得加载有点小慢,可能要好几秒。脚本----::::info[有点长]```javascript// ==UserScript==// @name 通用背景// @namespace https://www.luogu.com.cn/user/1486819// @version 1.2.1// @description 任何网站设置背景,支持上传/随机图床URL、手动/自动切换、平滑过渡、可拖动按钮// @author ArknightsEndfield// @license MIT// @match *://*/*// @grant GM_addStyle// @run-at document-idle// ==/UserScript==(function() {'use strict';// ===== 黑名单 =====const BLACKLIST = [// 'luogu.com.cn','oier.baoshuo.dev',];const host = window.location.hostname;const isBlocked = BLACKLIST.some(pattern => {if (pattern.includes('*')) {const regex = new RegExp('^' + pattern.replace(/\*/g, '.*') + '$');return regex.test(host);}return host.includes(pattern);});if (isBlocked) {console.log('[背景脚本] 当前网站已在黑名单中,跳过执行');return;}// ===== 只在顶层窗口运行(防止 iframe 嵌套导致重复加载) =====let isTopWindow = false;try {isTopWindow = (window.top === window.self);} catch (e) {isTopWindow = false;}if (!isTopWindow) {console.log('[背景脚本] 当前在 iframe 中,跳过执行');return;}// ===== 配置 =====const DB_NAME = 'BgDB';const STORE_NAME = 'media';const MAX_SIZE = 25 * 1024 * 1024;const DEFAULT_OPACITY = 0.1;const DEFAULT_BLUR = 0;const DEFAULT_BRIGHTNESS = 100;const DEFAULT_Z_INDEX = 0;const DEFAULT_AUTO_SWITCH = false;const DEFAULT_INTERVAL_HOURS = 0;const DEFAULT_INTERVAL_MINUTES = 0;const DEFAULT_INTERVAL_SECONDS = 10;const BTN_POS_KEY = 'ug_bg_btn_pos';// ----- IndexedDB -----function openDB() {return new Promise((resolve, reject) => {const req = indexedDB.open(DB_NAME, 1);req.onupgradeneeded = e => {const db = e.target.result;if (!db.objectStoreNames.contains(STORE_NAME)) {db.createObjectStore(STORE_NAME, { keyPath: 'id', autoIncrement: true });}};req.onsuccess = e => resolve(e.target.result);req.onerror = e => reject(e.target.error);});}async function dbSave(data, type, mime) {const db = await openDB();const tx = db.transaction(STORE_NAME, 'readwrite');const store = tx.objectStore(STORE_NAME);return new Promise((resolve, reject) => {const req = store.add({ data, type, mime, timestamp: Date.now() });req.onsuccess = () => resolve(req.result);req.onerror = () => reject(req.error);});}async function dbGetAll() {const db = await openDB();const tx = db.transaction(STORE_NAME, 'readonly');const store = tx.objectStore(STORE_NAME);return new Promise((resolve, reject) => {const req = store.getAll();req.onsuccess = () => resolve(req.result);req.onerror = () => reject(req.error);});}async function dbClear() {const db = await openDB();const tx = db.transaction(STORE_NAME, 'readwrite');const store = tx.objectStore(STORE_NAME);return new Promise((resolve, reject) => {const req = store.clear();req.onsuccess = () => resolve();req.onerror = () => reject(req.error);});}async function dbDelete(id) {const db = await openDB();const tx = db.transaction(STORE_NAME, 'readwrite');const store = tx.objectStore(STORE_NAME);return new Promise((resolve, reject) => {const req = store.delete(id);req.onsuccess = () => resolve();req.onerror = () => reject(req.error);});}// ----- 工具 -----function blobToArrayBuffer(blob) {return new Promise((resolve, reject) => {const r = new FileReader();r.onload = () => resolve(r.result);r.onerror = reject;r.readAsArrayBuffer(blob);});}function fileToDataURL(file) {return new Promise((resolve, reject) => {const reader = new FileReader();reader.onload = () => resolve(reader.result);reader.onerror = reject;reader.readAsDataURL(file);});}function mediaToUrl(media) {if (media.type === 'image') {if (typeof media.data === 'string' && media.data.startsWith('data:')) {return media.data;}try {const blob = new Blob([media.data], { type: media.mime });return URL.createObjectURL(blob);} catch (e) {return null;}} else if (media.type === 'video') {try {const blob = new Blob([media.data], { type: media.mime });return URL.createObjectURL(blob);} catch (e) {return null;}}return null;}function formatSize(bytes) {if (bytes < 1024) return bytes + 'B';if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + 'KB';return (bytes / (1024 * 1024)).toFixed(1) + 'MB';}// ----- 样式 -----GM_addStyle(`#ug-bg-layer {position: fixed;top: 0; left: 0;width: 100vw; height: 100vh;z-index: 0 !important;pointer-events: none !important;overflow: hidden;background: transparent !important;}#ug-bg-layer .ug-bg-media {position: absolute;top: 0; left: 0;width: 100%; height: 100%;object-fit: cover;transition: opacity 0.5s ease;opacity: 0;}#ug-bg-layer .ug-bg-media.active {opacity: 1;}#ug-bg-layer video, #ug-bg-layer img {width: 100%; height: 100%;object-fit: cover;position: absolute;top: 0; left: 0;}#ug-bg-panel {position: fixed;z-index: 9999999;top: 100px;left: 100px;width: 320px;max-height: 70vh;overflow-y: auto;background: rgba(30,30,46,0.95);backdrop-filter: blur(20px);border-radius: 16px;padding: 16px;color: #eee;font-family: -apple-system, sans-serif;font-size: 13px;border: 1px solid rgba(255,255,255,0.08);box-shadow: 0 12px 48px rgba(0,0,0,0.5);transition: opacity 0.25s;}#ug-bg-panel.collapsed {opacity: 0;pointer-events: none;display: none;}#ug-bg-panel .row { display: flex; gap: 6px; margin: 6px 0; flex-wrap: wrap; align-items: center; }#ug-bg-panel .btn {padding: 6px 12px;border: none;border-radius: 6px;font-size: 12px;font-weight: 600;cursor: pointer;transition: 0.2s;}#ug-bg-panel .btn-primary { background: #6c5ce7; color: #fff; }#ug-bg-panel .btn-primary:hover { background: #5a4bd1; }#ug-bg-panel .btn-secondary { background: rgba(255,255,255,0.1); color: #ccc; }#ug-bg-panel .btn-secondary:hover { background: rgba(255,255,255,0.2); }#ug-bg-panel .btn-danger { background: #e74c3c; color: #fff; }#ug-bg-panel .btn-danger:hover { background: #c0392b; }#ug-bg-panel .btn-sm { padding: 4px 8px; font-size: 11px; }#ug-bg-panel .btn-success { background: #2ecc71; color: #fff; }#ug-bg-panel .btn-success:hover { background: #27ae60; }#ug-bg-panel .media-list { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; }#ug-bg-panel .media-item {position: relative;width: 50px; height: 50px;border-radius: 6px;border: 2px solid transparent;cursor: pointer;overflow: hidden;background: #222;}#ug-bg-panel .media-item.active { border-color: #6c5ce7; }#ug-bg-panel .media-item img, #ug-bg-panel .media-item video {width: 100%; height: 100%;object-fit: cover;}#ug-bg-panel .media-item .del {position: absolute;top: 0; right: 0;background: rgba(231,76,60,0.8);color: #fff;border: none;width: 16px; height: 16px;font-size: 10px;cursor: pointer;border-radius: 0 6px 0 6px;}#ug-bg-panel .hint { font-size: 11px; color: #666; margin-top: 4px; }#ug-bg-panel .slider-group {display: flex;align-items: center;gap: 10px;margin: 6px 0;}#ug-bg-panel .slider-group label {min-width: 50px;font-size: 12px;color: #aaa;text-align: right;}#ug-bg-panel .slider-group input[type="range"] {flex: 1;-webkit-appearance: none;height: 4px;border-radius: 2px;background: rgba(255,255,255,0.15);outline: none;}#ug-bg-panel .slider-group input[type="range"]::-webkit-slider-thumb {-webkit-appearance: none;width: 16px; height: 16px;border-radius: 50%;background: #6c5ce7;border: 2px solid #fff;cursor: pointer;}#ug-bg-panel .slider-group input[type="range"]::-moz-range-thumb {width: 16px; height: 16px;border-radius: 50%;background: #6c5ce7;border: 2px solid #fff;cursor: pointer;}#ug-bg-panel .val-display {min-width: 36px;text-align: center;font-size: 11px;font-weight: 600;color: #a29bfe;background: rgba(108,92,231,0.15);padding: 2px 6px;border-radius: 4px;}#ug-bg-panel .auto-input {width: 40px;background: #222;color: #fff;border: 1px solid #555;border-radius: 4px;padding: 2px 4px;text-align: center;font-size: 12px;}#ug-bg-panel .auto-input:focus {outline: none;border-color: #6c5ce7;}#ug-bg-panel .auto-status {font-size: 11px;color: #888;margin-top: 4px;}#ug-bg-panel .url-input {flex: 1;min-width: 180px;padding: 6px 10px;background: #222;color: #eee;border: 1px solid #555;border-radius: 6px;font-size: 12px;}#ug-bg-panel .url-input:focus {outline: none;border-color: #6c5ce7;}#ug-bg-toggle-btn {position: fixed;bottom: 30px;right: 30px;z-index: 9999998;width: 48px; height: 48px;border-radius: 50%;background: rgba(30,30,46,0.85);backdrop-filter: blur(12px);border: 1px solid rgba(255,255,255,0.1);color: #fff;font-size: 20px;cursor: grab;box-shadow: 0 4px 20px rgba(0,0,0,0.3);display: flex;align-items: center;justify-content: center;transition: background 0.2s;user-select: none;touch-action: none;}#ug-bg-toggle-btn:hover { background: rgba(108,92,231,0.85); }#ug-bg-toggle-btn:active { cursor: grabbing; }#ug-bg-toast {position: fixed;bottom: 90px;right: 90px;z-index: 9999999;background: rgba(0,0,0,0.8);color: #fff;padding: 8px 16px;border-radius: 8px;font-size: 13px;opacity: 0;transition: opacity 0.3s;pointer-events: none;}#ug-bg-toast.show { opacity: 1; }`);// ----- Toast -----function showToast(msg, duration = 2000) {let t = document.getElementById('ug-bg-toast');if (!t) {t = document.createElement('div');t.id = 'ug-bg-toast';document.body.appendChild(t);}t.textContent = msg;t.classList.add('show');clearTimeout(t._timer);t._timer = setTimeout(() => t.classList.remove('show'), duration);}// ===== 状态管理 =====function loadState() {try {const raw = localStorage.getItem('ug_bg_state');if (raw) {const parsed = JSON.parse(raw);if (parsed.opacity === undefined || parsed.opacity === null) parsed.opacity = DEFAULT_OPACITY;if (parsed.blur === undefined || parsed.blur === null) parsed.blur = DEFAULT_BLUR;if (parsed.brightness === undefined || parsed.brightness === null) parsed.brightness = DEFAULT_BRIGHTNESS;if (parsed.zIndex === undefined || parsed.zIndex === null) parsed.zIndex = DEFAULT_Z_INDEX;if (parsed.autoSwitch === undefined || parsed.autoSwitch === null) parsed.autoSwitch = DEFAULT_AUTO_SWITCH;if (parsed.intervalHours === undefined || parsed.intervalHours === null) parsed.intervalHours = DEFAULT_INTERVAL_HOURS;if (parsed.intervalMinutes === undefined || parsed.intervalMinutes === null) parsed.intervalMinutes = DEFAULT_INTERVAL_MINUTES;if (parsed.intervalSeconds === undefined || parsed.intervalSeconds === null) parsed.intervalSeconds = DEFAULT_INTERVAL_SECONDS;return parsed;}} catch (e) {}return {selectedId: null,opacity: DEFAULT_OPACITY,blur: DEFAULT_BLUR,brightness: DEFAULT_BRIGHTNESS,zIndex: DEFAULT_Z_INDEX,autoSwitch: DEFAULT_AUTO_SWITCH,intervalHours: DEFAULT_INTERVAL_HOURS,intervalMinutes: DEFAULT_INTERVAL_MINUTES,intervalSeconds: DEFAULT_INTERVAL_SECONDS};}function saveState(state) {localStorage.setItem('ug_bg_state', JSON.stringify(state));}// ===== 应用层级 =====function applyZIndex(zIndex) {const layer = document.getElementById('ug-bg-layer');if (layer) {layer.style.setProperty('z-index', String(zIndex), 'important');}}// ===== 滤镜应用 =====function applyFilter(blur, brightness, el) {if (!el) {const layer = document.getElementById('ug-bg-layer');if (layer) el = layer.querySelector('.ug-bg-media.active');}if (el) {el.style.filter = `blur(${blur || 0}px) brightness(${(brightness || 100) / 100})`;}}// ===== 渲染背景(支持 remote 类型:直接赋 URL,绕过 CORS) =====async function renderBg(media) {const layer = document.getElementById('ug-bg-layer');if (!layer) {const newLayer = document.createElement('div');newLayer.id = 'ug-bg-layer';document.body.prepend(newLayer);await renderBg(media);return;}if (!media) {layer.innerHTML = '';return;}const state = loadState();const currentOpacity = state.opacity !== undefined ? state.opacity : DEFAULT_OPACITY;const currentZIndex = state.zIndex !== undefined ? state.zIndex : DEFAULT_Z_INDEX;layer.style.position = 'fixed';layer.style.top = '0';layer.style.left = '0';layer.style.width = '100vw';layer.style.height = '100vh';layer.style.overflow = 'hidden';layer.style.display = 'block';layer.style.background = 'transparent';layer.style.setProperty('z-index', String(currentZIndex), 'important');layer.style.setProperty('pointer-events', 'none', 'important');layer.style.setProperty('opacity', String(currentOpacity), 'important');// 获取 URL(remote 类型直接赋 URL,加时间戳破缓存)let url;let isRemote = false;if (media.type === 'remote') {const sep = media.data.includes('?') ? '&' : '?';url = media.data + sep + '_t=' + Date.now();isRemote = true;} else {url = mediaToUrl(media);if (!url) {showToast('❌ 生成URL失败,请检查文件格式');return;}}let newEl;if (media.type === 'video') {newEl = document.createElement('video');newEl.src = url;newEl.muted = true;newEl.loop = true;newEl.playsInline = true;newEl.addEventListener('loadeddata', () => {newEl.play().catch(() => {});});newEl.onerror = () => {showToast('❌ 视频加载失败,可能格式不支持');if (newEl.parentNode) newEl.remove();};} else {// image 或 remote 都当图片处理newEl = document.createElement('img');if (isRemote) {// 防止防盗链;不加 crossOrigin 以避免 CORS 头缺失导致的加载失败newEl.referrerPolicy = 'no-referrer';}newEl.src = url;newEl.onerror = () => {showToast('❌ 图片加载失败,可能防盗链或格式不支持');if (newEl.parentNode) newEl.remove();};}newEl.className = 'ug-bg-media';const blur = state.blur || 0;const brightness = state.brightness || 100;newEl.style.filter = `blur(${blur}px) brightness(${brightness / 100})`;layer.appendChild(newEl);let loadResolve = () => {};const loadPromise = new Promise(resolve => { loadResolve = resolve; });const finishLoad = () => loadResolve();if (media.type === 'video') {if (newEl.readyState >= 2) {finishLoad();} else {newEl.addEventListener('loadeddata', finishLoad);const origError = newEl.onerror;newEl.onerror = (e) => {if (origError) origError(e);finishLoad();};}} else {if (newEl.complete && newEl.naturalWidth > 0) {finishLoad();} else {newEl.onload = finishLoad;const origError = newEl.onerror;newEl.onerror = (e) => {if (origError) origError(e);finishLoad();};}}loadPromise.then(() => {const oldActiveEl = layer.querySelector('.ug-bg-media.active');if (oldActiveEl && oldActiveEl !== newEl) {oldActiveEl.classList.remove('active');const onTransitionEnd = () => {oldActiveEl.removeEventListener('transitionend', onTransitionEnd);if (oldActiveEl.parentNode) oldActiveEl.remove();};oldActiveEl.addEventListener('transitionend', onTransitionEnd);setTimeout(() => {if (oldActiveEl.parentNode) {oldActiveEl.removeEventListener('transitionend', onTransitionEnd);oldActiveEl.remove();}}, 1000);}newEl.classList.add('active');applyFilter(state.blur, state.brightness, newEl);if (media.type === 'video') {newEl.play().catch(() => {});}resetAutoTimer();});setTimeout(() => {if (!newEl.classList.contains('active')) {const oldActiveEl = layer.querySelector('.ug-bg-media.active');if (oldActiveEl && oldActiveEl !== newEl) {oldActiveEl.classList.remove('active');setTimeout(() => {if (oldActiveEl.parentNode) oldActiveEl.remove();}, 600);}newEl.classList.add('active');applyFilter(state.blur, state.brightness, newEl);if (media.type === 'video') {newEl.play().catch(() => {});}resetAutoTimer();}}, 5000);}// ===== 自动切换相关 =====let switchTimer = null;async function switchToNextBg() {const all = await dbGetAll();if (all.length === 0) {showToast('⚠️ 无媒体可切换');return;}const state = loadState();let currentId = state.selectedId;if (!currentId || !all.some(m => m.id === currentId)) {currentId = all[0].id;} else {const index = all.findIndex(m => m.id === currentId);const nextIndex = (index + 1) % all.length;currentId = all[nextIndex].id;}const media = all.find(m => m.id === currentId);if (media) {state.selectedId = currentId;saveState(state);await renderBg(media);const p = document.getElementById('ug-bg-panel');if (p && !p.classList.contains('collapsed')) {await showPanel(state);}}}function startAutoSwitch() {stopAutoSwitch();const state = loadState();const hours = parseInt(state.intervalHours) || 0;const minutes = parseInt(state.intervalMinutes) || 0;const seconds = parseInt(state.intervalSeconds) || 0;const totalMs = (hours * 3600 + minutes * 60 + seconds) * 1000;if (totalMs < 1000) {showToast('⚠️ 间隔时间至少 1 秒');return;}state.autoSwitch = true;saveState(state);switchTimer = setInterval(switchToNextBg, totalMs);updateAutoStatus(true, totalMs);showToast(`✅ 自动切换已启动(间隔 ${hours}时 ${minutes}分 ${seconds}秒)`);}function stopAutoSwitch() {if (switchTimer) {clearInterval(switchTimer);switchTimer = null;}const state = loadState();state.autoSwitch = false;saveState(state);updateAutoStatus(false, 0);showToast('⏹️ 自动切换已停止');}function resetAutoTimer() {const state = loadState();if (state.autoSwitch) {if (switchTimer) {clearInterval(switchTimer);switchTimer = null;}const hours = parseInt(state.intervalHours) || 0;const minutes = parseInt(state.intervalMinutes) || 0;const seconds = parseInt(state.intervalSeconds) || 0;const totalMs = (hours * 3600 + minutes * 60 + seconds) * 1000;if (totalMs >= 1000) {state.autoSwitch = true;saveState(state);switchTimer = setInterval(switchToNextBg, totalMs);updateAutoStatus(true, totalMs);} else {state.autoSwitch = false;saveState(state);updateAutoStatus(false, 0);}}}function updateAutoStatus(isRunning, intervalMs) {const statusEl = document.getElementById('ug-auto-status');if (statusEl) {if (isRunning) {const sec = Math.floor(intervalMs / 1000);const h = Math.floor(sec / 3600);const m = Math.floor((sec % 3600) / 60);const s = sec % 60;statusEl.textContent = `✅ 运行中 (间隔 ${h}h ${m}m ${s}s)`;statusEl.style.color = '#2ecc71';} else {statusEl.textContent = '⏹️ 已停止';statusEl.style.color = '#888';}}}// ===== 面板位置跟随按钮 =====function updatePanelPosition() {const p = document.getElementById('ug-bg-panel');const btn = document.getElementById('ug-bg-toggle-btn');if (!p || !btn) return;if (p.classList.contains('collapsed')) return;const btnRect = btn.getBoundingClientRect();const panelW = p.offsetWidth || 320;const panelH = p.offsetHeight || 400;const gap = 12;const margin = 10;let left;if (btnRect.left - gap - panelW >= margin) {left = btnRect.left - gap - panelW;} else if (btnRect.right + gap + panelW <= window.innerWidth - margin) {left = btnRect.right + gap;} else {left = Math.max(margin, Math.min(window.innerWidth - panelW - margin, btnRect.left + btnRect.width / 2 - panelW / 2));}let top = btnRect.bottom - panelH;if (top < margin) top = margin;if (top + panelH > window.innerHeight - margin) {top = window.innerHeight - panelH - margin;}p.style.left = left + 'px';p.style.top = top + 'px';p.style.right = 'auto';p.style.bottom = 'auto';}// ===== 可拖动按钮 =====function createToggleButton() {if (document.getElementById('ug-bg-toggle-btn')) return;if (!document.body) {setTimeout(createToggleButton, 100);return;}const btn = document.createElement('div');btn.id = 'ug-bg-toggle-btn';btn.textContent = '🎨';try {const pos = JSON.parse(localStorage.getItem(BTN_POS_KEY) || 'null');if (pos && typeof pos.left === 'number' && typeof pos.top === 'number') {const maxLeft = Math.max(0, window.innerWidth - 48);const maxTop = Math.max(0, window.innerHeight - 48);const left = Math.min(Math.max(0, pos.left), maxLeft);const top = Math.min(Math.max(0, pos.top), maxTop);btn.style.left = left + 'px';btn.style.top = top + 'px';btn.style.right = 'auto';btn.style.bottom = 'auto';}} catch (e) {}let isDragging = false;let hasMoved = false;let startX = 0, startY = 0, startLeft = 0, startTop = 0;btn.addEventListener('pointerdown', (e) => {if (e.button !== 0 && e.pointerType === 'mouse') return;isDragging = true;hasMoved = false;startX = e.clientX;startY = e.clientY;const rect = btn.getBoundingClientRect();startLeft = rect.left;startTop = rect.top;try { btn.setPointerCapture(e.pointerId); } catch (err) {}e.preventDefault();});btn.addEventListener('pointermove', (e) => {if (!isDragging) return;const dx = e.clientX - startX;const dy = e.clientY - startY;if (!hasMoved && (Math.abs(dx) > 3 || Math.abs(dy) > 3)) {hasMoved = true;}if (!hasMoved) return;const w = btn.offsetWidth || 48;const h = btn.offsetHeight || 48;const newLeft = Math.max(0, Math.min(window.innerWidth - w, startLeft + dx));const newTop = Math.max(0, Math.min(window.innerHeight - h, startTop + dy));btn.style.left = newLeft + 'px';btn.style.top = newTop + 'px';btn.style.right = 'auto';btn.style.bottom = 'auto';});const endDrag = (e) => {if (!isDragging) return;isDragging = false;try { btn.releasePointerCapture(e.pointerId); } catch (err) {}if (hasMoved) {const left = parseInt(btn.style.left, 10) || 0;const top = parseInt(btn.style.top, 10) || 0;localStorage.setItem(BTN_POS_KEY, JSON.stringify({ left, top }));updatePanelPosition();}};btn.addEventListener('pointerup', endDrag);btn.addEventListener('pointercancel', endDrag);btn.addEventListener('click', (e) => {if (hasMoved) {e.stopPropagation();e.preventDefault();hasMoved = false;return;}togglePanel();});document.body.appendChild(btn);}// ===== 面板 =====let panelVisible = false;let panel = null;async function togglePanel() {const state = loadState();panelVisible = !panelVisible;if (panelVisible) {await showPanel(state);} else {const p = document.getElementById('ug-bg-panel');if (p) p.classList.add('collapsed');}}async function showPanel(state) {if (!panel) {panel = document.createElement('div');panel.id = 'ug-bg-panel';document.body.appendChild(panel);}panel.classList.remove('collapsed');const all = await dbGetAll();let listHtml = '';if (all.length === 0) {listHtml = '<span style="color:#666;font-size:12px;">暂无媒体</span>';} else {listHtml = all.map(m => {const active = m.id === state.selectedId ? 'active' : '';if (m.type === 'remote') {return `<div class="media-item ${active}" data-id="${m.id}" title="随机图床: ${m.data}" style="background:#2a2a3e;display:flex;align-items:center;justify-content:center;font-size:22px;">🌐<button class="del" data-id="${m.id}">×</button></div>`;}const url = mediaToUrl(m);if (!url) return `<div class="media-item" style="border-color:red;">⚠️</div>`;return `<div class="media-item ${active}" data-id="${m.id}">${m.type === 'image' ? `<img src="${url}">` : `<video src="${url}" muted></video>`}<button class="del" data-id="${m.id}">×</button></div>`;}).join('');}const currentOpacity = state.opacity !== undefined ? state.opacity : DEFAULT_OPACITY;const currentBlur = state.blur !== undefined ? state.blur : DEFAULT_BLUR;const currentBrightness = state.brightness !== undefined ? state.brightness : DEFAULT_BRIGHTNESS;const currentZIndex = state.zIndex !== undefined ? state.zIndex : DEFAULT_Z_INDEX;const autoSwitch = state.autoSwitch || false;const h = state.intervalHours || 0;const m = state.intervalMinutes || 0;const s = state.intervalSeconds || 10;panel.innerHTML = `<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;"><span style="font-weight:700;font-size:15px;">🎨 背景设置</span><button class="btn btn-secondary btn-sm" id="ug-panel-close">✕</button></div><div class="row"><button class="btn btn-primary btn-sm" id="ug-upload-img">📷 图片</button><button class="btn btn-primary btn-sm" id="ug-upload-video">🎬 视频</button><button class="btn btn-success btn-sm" id="ug-test-video">🎬 测试</button><button class="btn btn-danger btn-sm" id="ug-clear-all">清空</button></div><div class="hint">上传 ≤ 25MB · 点击页面播放视频 · 默认透明度 0.1</div><div style="margin-top:8px;display:flex;gap:6px;align-items:center;flex-wrap:wrap;"><input type="text" id="ug-remote-input" placeholder="图床" class="url-input"><button class="btn btn-success btn-sm" id="ug-remote-add">🌐 添加随机</button></div><div class="hint"></div><div style="margin:10px 0;"><div class="slider-group"><label>模糊</label><input type="range" id="ug-slider-blur" min="0" max="30" value="${currentBlur}" step="1"><span class="val-display" id="ug-val-blur">${currentBlur}px</span></div><div class="slider-group"><label>亮度</label><input type="range" id="ug-slider-brightness" min="10" max="200" value="${currentBrightness}" step="5"><span class="val-display" id="ug-val-brightness">${currentBrightness}%</span></div><div class="slider-group"><label>透明度</label><input type="range" id="ug-slider-opacity" min="0" max="100" value="${Math.round(currentOpacity * 100)}" step="5"><span class="val-display" id="ug-val-opacity">${Math.round(currentOpacity * 100)}%</span></div><div class="slider-group"><label>层级</label><input type="range" id="ug-slider-zindex" min="-10" max="50" value="${currentZIndex}" step="1"><span class="val-display" id="ug-val-zindex">${currentZIndex}</span></div></div><div style="margin-top:10px;border-top:1px solid #444;padding-top:10px;"><div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;"><span style="font-size:12px;color:#aaa;">自动切换</span><input type="number" id="ug-auto-hours" min="0" max="23" value="${h}" class="auto-input">时<input type="number" id="ug-auto-minutes" min="0" max="59" value="${m}" class="auto-input">分<input type="number" id="ug-auto-seconds" min="0" max="59" value="${s}" class="auto-input">秒<button class="btn btn-primary btn-sm" id="ug-auto-start">▶ 启动</button><button class="btn btn-danger btn-sm" id="ug-auto-stop">⏹ 停止</button></div><div id="ug-auto-status" class="auto-status">${autoSwitch ? '✅ 运行中' : '⏹️ 已停止'}</div></div><div style="margin-top:10px;"><div style="font-size:12px;color:#888;">已保存 (${all.length})</div><div class="media-list">${listHtml}</div></div><div style="margin-top:12px;font-size:11px;color:#555;text-align:center;">点击缩略图切换背景</div>`;requestAnimationFrame(updatePanelPosition);panel.querySelector('#ug-panel-close').addEventListener('click', togglePanel);// 上传图片panel.querySelector('#ug-upload-img').addEventListener('click', () => {const inp = document.createElement('input');inp.type = 'file';inp.accept = 'image/*';inp.onchange = async e => {const f = e.target.files[0];if (!f) return;if (f.size > MAX_SIZE) {alert(`文件 ${formatSize(f.size)} 超过 25MB`);return;}try {const dataUrl = await fileToDataURL(f);const id = await dbSave(dataUrl, 'image', f.type);const state = loadState();state.selectedId = id;saveState(state);const all = await dbGetAll();const media = all.find(m => m.id === id);await renderBg(media);await showPanel(state);showToast('✅ 图片已保存');} catch (err) {showToast('❌ 图片保存失败: ' + err.message);}};inp.click();});// 上传视频panel.querySelector('#ug-upload-video').addEventListener('click', () => {const inp = document.createElement('input');inp.type = 'file';inp.accept = 'video/mp4,video/webm,video/*';inp.onchange = async e => {const f = e.target.files[0];if (!f) return;if (f.size > MAX_SIZE) {alert(`文件 ${formatSize(f.size)} 超过 25MB`);return;}try {const buf = await blobToArrayBuffer(f);const id = await dbSave(buf, 'video', f.type);const state = loadState();state.selectedId = id;saveState(state);const all = await dbGetAll();const media = all.find(m => m.id === id);await renderBg(media);await showPanel(state);showToast('✅ 视频已保存');} catch (err) {showToast('❌ 视频保存失败: ' + err.message);}};inp.click();});// 测试视频panel.querySelector('#ug-test-video').addEventListener('click', async () => {try {const testUrl = 'https://www.w3schools.com/html/mov_bbb.mp4';const resp = await fetch(testUrl);if (!resp.ok) throw new Error('网络错误');const blob = await resp.blob();if (!blob.type.startsWith('video/')) throw new Error('不是视频格式');const buf = await blobToArrayBuffer(blob);const id = await dbSave(buf, 'video', blob.type);const state = loadState();state.selectedId = id;saveState(state);const all = await dbGetAll();const media = all.find(m => m.id === id);await renderBg(media);await showPanel(state);showToast('✅ 测试视频已加载');} catch (err) {showToast('❌ 测试视频失败: ' + err.message);}});// 添加图床链(直接存 URL,不 fetch)panel.querySelector('#ug-remote-add').addEventListener('click', async () => {const input = panel.querySelector('#ug-remote-input');const rawUrl = (input.value || '').trim();if (!rawUrl) { showToast('⚠️ 请输入 URL'); return; }if (!/^https?:\/\//i.test(rawUrl)) { showToast('⚠️ URL 必须以 http(s):// 开头'); return; }try {const id = await dbSave(rawUrl, 'remote', 'image/*');const state = loadState();state.selectedId = id;saveState(state);const all = await dbGetAll();const media = all.find(m => m.id === id);await renderBg(media);input.value = '';await showPanel(state);showToast('✅ 随机图床已添加');} catch (err) {showToast('❌ 保存失败: ' + err.message);}});// 清空panel.querySelector('#ug-clear-all').addEventListener('click', async () => {if (confirm('清空所有背景?')) {await dbClear();const state = loadState();state.selectedId = null;saveState(state);await renderBg(null);await showPanel(state);showToast('已清空');if (state.autoSwitch) stopAutoSwitch();}});// 点击缩略图panel.querySelectorAll('.media-item').forEach(el => {el.addEventListener('click', async e => {if (e.target.closest('.del')) return;const id = Number(el.dataset.id);const all = await dbGetAll();const media = all.find(m => m.id === id);if (media) {const state = loadState();state.selectedId = id;saveState(state);await renderBg(media);await showPanel(state);}});});// 删除panel.querySelectorAll('.del').forEach(el => {el.addEventListener('click', async e => {e.stopPropagation();const id = Number(el.dataset.id);await dbDelete(id);const state = loadState();if (state.selectedId === id) {state.selectedId = null;saveState(state);await renderBg(null);}await showPanel(state);});});// 透明度滑块const opacitySlider = panel.querySelector('#ug-slider-opacity');const opacityDisplay = panel.querySelector('#ug-val-opacity');opacitySlider.addEventListener('input', () => {const val = parseInt(opacitySlider.value) / 100;opacityDisplay.textContent = Math.round(val * 100) + '%';const layer = document.getElementById('ug-bg-layer');if (layer) {layer.style.setProperty('opacity', String(val), 'important');}const state = loadState();state.opacity = val;saveState(state);});// 模糊滑块const blurSlider = panel.querySelector('#ug-slider-blur');const blurDisplay = panel.querySelector('#ug-val-blur');blurSlider.addEventListener('input', () => {const val = parseInt(blurSlider.value);blurDisplay.textContent = val + 'px';const state = loadState();state.blur = val;saveState(state);const layer = document.getElementById('ug-bg-layer');const activeEl = layer ? layer.querySelector('.ug-bg-media.active') : null;applyFilter(val, state.brightness, activeEl);});// 亮度滑块const brightSlider = panel.querySelector('#ug-slider-brightness');const brightDisplay = panel.querySelector('#ug-val-brightness');brightSlider.addEventListener('input', () => {const val = parseInt(brightSlider.value);brightDisplay.textContent = val + '%';const state = loadState();state.brightness = val;saveState(state);const layer = document.getElementById('ug-bg-layer');const activeEl = layer ? layer.querySelector('.ug-bg-media.active') : null;applyFilter(state.blur, val, activeEl);});// 层级滑块const zIndexSlider = panel.querySelector('#ug-slider-zindex');const zIndexDisplay = panel.querySelector('#ug-val-zindex');zIndexSlider.addEventListener('input', () => {const val = parseInt(zIndexSlider.value);zIndexDisplay.textContent = val;const state = loadState();state.zIndex = val;saveState(state);applyZIndex(val);});// 自动切换const autoStartBtn = panel.querySelector('#ug-auto-start');const autoStopBtn = panel.querySelector('#ug-auto-stop');const hoursInput = panel.querySelector('#ug-auto-hours');const minutesInput = panel.querySelector('#ug-auto-minutes');const secondsInput = panel.querySelector('#ug-auto-seconds');autoStartBtn.addEventListener('click', () => {const state = loadState();state.intervalHours = parseInt(hoursInput.value) || 0;state.intervalMinutes = parseInt(minutesInput.value) || 0;state.intervalSeconds = parseInt(secondsInput.value) || 0;saveState(state);startAutoSwitch();});autoStopBtn.addEventListener('click', stopAutoSwitch);if (state.autoSwitch) {const totalMs = ((state.intervalHours || 0) * 3600 + (state.intervalMinutes || 0) * 60 + (state.intervalSeconds || 0)) * 1000;updateAutoStatus(true, totalMs);}}// ===== 守护(setInterval 检查) =====let watchTimer = null;function startPatchWatcher() {if (watchTimer) clearInterval(watchTimer);const check = () => {if (!document.body) return;if (!document.getElementById('ug-bg-layer')) {const state = loadState();if (state.selectedId) {dbGetAll().then(all => {const media = all.find(m => m.id === state.selectedId);if (media && !document.getElementById('ug-bg-layer')) {renderBg(media);}});}}if (!document.getElementById('ug-bg-toggle-btn')) {createToggleButton();}};check();watchTimer = setInterval(check, 1500);}// ===== 窗口大小改变 =====let resizeRaf = null;window.addEventListener('resize', () => {if (resizeRaf) return;resizeRaf = requestAnimationFrame(() => {resizeRaf = null;updatePanelPosition();const btn = document.getElementById('ug-bg-toggle-btn');if (btn && btn.style.left) {const w = btn.offsetWidth || 48;const h = btn.offsetHeight || 48;const left = Math.min(parseInt(btn.style.left, 10) || 0, window.innerWidth - w);const top = Math.min(parseInt(btn.style.top, 10) || 0, window.innerHeight - h);btn.style.left = Math.max(0, left) + 'px';btn.style.top = Math.max(0, top) + 'px';}});});// ----- 初始化 -----async function init() {try {createToggleButton();const state = loadState();if (state.selectedId) {const all = await dbGetAll();const media = all.find(m => m.id === state.selectedId);if (media) {await renderBg(media);} else {state.selectedId = null;saveState(state);}}startPatchWatcher();if (state.autoSwitch) {const totalMs = ((state.intervalHours || 0) * 3600 + (state.intervalMinutes || 0) * 60 + (state.intervalSeconds || 0)) * 1000;if (totalMs >= 1000) {startAutoSwitch();} else {state.autoSwitch = false;saveState(state);}}document.addEventListener('click', () => {const video = document.querySelector('#ug-bg-layer .ug-bg-media.active');if (video && video.paused && video.tagName === 'VIDEO') {video.play().catch(() => {});}}, { once: false });console.log('[初始化] 🎨 通用背景 v1.2.1 已启动(remote 直接赋 URL)');} catch (e) {console.error('[初始化] 启动失败:', e);}}if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', init);} else {init();}})();```123456786 行未改动15161718192021222324252627282930312 行未改动3435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510~~话说这玩意到底投哪个板块啊,投太多不会被封号吧qwq~~2026.11.27效果展示(deepseek/atcoder/QQ浏览器-新标签页/洛谷部分页面)---6 行未改动首先,本脚本肯定使用了deepseek。无论是学习这个语言还是后期更改。并且似乎和洛谷不太适配。(但是后面作者发现只要自己新建一个主题然后去掉洛谷自带的背景就可以正常用了。——2026.8.3 21:32:50)[洛谷专用——他人](https://www.luogu.com.cn/article/k0wlh572)如何使用---- 很显然,你需要一个tempermonkey。不过似乎有人不知道。- 首先,点开右上角菜单,找到“扩展”/“插件”,- 点进去,找到“获取拓展”。- 搜索tempermonkey,下载。- 新建脚本,Ctrl+S保存。它就自动启动了。- 如果不行的话,点击右上角拓展图标。- 管理拓展。- 找到tempermonkey的详细信息。- 全部勾选。- 启动脚本后刷新网页。然后点击右下角的🎨按钮,点击图片/视频,就可以添加了。如果看不到图,就调一下层级,因为不同网站它文字的层级不同。甚至有的网站它文字框(有的甚至没有文字框)是和背景同一层级的,所以说,您的图片只能置顶了(调一下透明度就好啦)。小问题-----2 行未改动目前已知问题网站 [QQ邮箱](mail.qq.com)更新预告------ 暂无更新日志----- 2026.2.26 OK,现在可以在洛谷上用了。但是bug好多(不太适配),还是建议找单独适用洛谷的脚本。如果硬要用这个,在黑名单里剔除就好。——已修。现在完全可以适配。- 2026.2.27 将视频限制上调为25MB,支持定时更换背景。- 2026.9.24 可以拖动的按钮,但是似乎有点问题???- 2026.10.11 可以直接从一些网站的图床上传图片。不用再下载到本地。但是这会使得加载有点小慢,可能要好几秒。- 2026.10.21- 更丝滑的背景转换。- 切换背景时的某些问题。- 按钮的修复。- 2026.11.27- 可以一次性上传大量的图片,不用再一个一个上传了。然后给大家一个很好的图源。[出门右转](https://www.luogu.com.cn/article/ldmeupsj)脚本----::::info[有点长]```javascript// ==UserScript==// @name 通用背景(pro)// @namespace https://www.luogu.com.cn/user/1486819// @version 1.4.0// @description 在大部分网站设置背景,支持批量上传图片、上传视频/图床URL、手动/自动切换、可拖动按钮// @author XiArk// @license MIT// @match *://*/*// @grant GM_addStyle// @run-at document-idle// ==/UserScript==(function() {'use strict';// ===== 黑名单 =====const BLACKLIST = [// 'luogu.com.cn','oier.baoshuo.dev',];const host = window.location.hostname;const isBlocked = BLACKLIST.some(pattern => {if (pattern.includes('*')) {const regex = new RegExp('^' + pattern.replace(/\*/g, '.*') + '$');return regex.test(host);}return host.includes(pattern);});if (isBlocked) {console.log('[背景脚本] 当前网站已在黑名单中,跳过执行');return;}// ===== 只在顶层窗口运行 =====let isTopWindow = false;try {isTopWindow = (window.top === window.self);} catch (e) {isTopWindow = false;}if (!isTopWindow) return;// ===== 配置 =====const DB_NAME = 'BgDB';const STORE_NAME = 'media';const MAX_SIZE = 25 * 1024 * 1024;const DEFAULT_OPACITY = 0.1;const DEFAULT_BLUR = 0;const DEFAULT_BRIGHTNESS = 100;const DEFAULT_Z_INDEX = 0;const DEFAULT_AUTO_SWITCH = false;const DEFAULT_INTERVAL_HOURS = 0;const DEFAULT_INTERVAL_MINUTES = 0;const DEFAULT_INTERVAL_SECONDS = 10;const BTN_POS_KEY = 'ug_bg_btn_pos';const SEEN_AD_KEY = 'ug_bg_seen_ad'; // 是否看过首次广告// ----- IndexedDB -----function openDB() {return new Promise((resolve, reject) => {const req = indexedDB.open(DB_NAME, 1);req.onupgradeneeded = e => {const db = e.target.result;if (!db.objectStoreNames.contains(STORE_NAME)) {db.createObjectStore(STORE_NAME, { keyPath: 'id', autoIncrement: true });}};req.onsuccess = e => resolve(e.target.result);req.onerror = e => reject(e.target.error);});}async function dbSave(data, type, mime) {const db = await openDB();const tx = db.transaction(STORE_NAME, 'readwrite');const store = tx.objectStore(STORE_NAME);return new Promise((resolve, reject) => {const req = store.add({ data, type, mime, timestamp: Date.now() });req.onsuccess = () => resolve(req.result);req.onerror = () => reject(req.error);});}// 批量保存:所有图片共用一个 IndexedDB 事务,避免逐张打开事务、逐张刷新界面。async function dbSaveMany(items) {const db = await openDB();return new Promise((resolve, reject) => {const tx = db.transaction(STORE_NAME, 'readwrite');const store = tx.objectStore(STORE_NAME);const ids = [];let requestError = null;for (const item of items) {const req = store.add({data: item.data,type: item.type,mime: item.mime,timestamp: Date.now()});req.onsuccess = () => { ids.push(req.result); };req.onerror = () => {requestError = req.error || new Error('写入失败');};}tx.oncomplete = () => resolve(ids);tx.onerror = () => reject(requestError || tx.error || new Error('批量保存失败'));tx.onabort = () => reject(requestError || tx.error || new Error('批量保存已中止'));});}async function dbGetAll() {const db = await openDB();const tx = db.transaction(STORE_NAME, 'readonly');const store = tx.objectStore(STORE_NAME);return new Promise((resolve, reject) => {const req = store.getAll();req.onsuccess = () => resolve(req.result);req.onerror = () => reject(req.error);});}async function dbClear() {const db = await openDB();const tx = db.transaction(STORE_NAME, 'readwrite');const store = tx.objectStore(STORE_NAME);return new Promise((resolve, reject) => {const req = store.clear();req.onsuccess = () => resolve();req.onerror = () => reject(req.error);});}async function dbDelete(id) {const db = await openDB();const tx = db.transaction(STORE_NAME, 'readwrite');const store = tx.objectStore(STORE_NAME);return new Promise((resolve, reject) => {const req = store.delete(id);req.onsuccess = () => resolve();req.onerror = () => reject(req.error);});}// ----- 工具 -----function blobToArrayBuffer(blob) {return new Promise((resolve, reject) => {const r = new FileReader();r.onload = () => resolve(r.result);r.onerror = reject;r.readAsArrayBuffer(blob);});}function fileToDataURL(file) {return new Promise((resolve, reject) => {const reader = new FileReader();reader.onload = () => resolve(reader.result);reader.onerror = reject;reader.readAsDataURL(file);});}function mediaToUrl(media) {if (media.type === 'image') {if (typeof media.data === 'string' && media.data.startsWith('data:')) {return media.data;}try {// 新上传的图片直接以 Blob 存储,避免转成 Base64 带来的额外耗时和体积。const blob = media.data instanceof Blob? media.data: new Blob([media.data], { type: media.mime });return URL.createObjectURL(blob);} catch (e) {return null;}} else if (media.type === 'video') {try {const blob = new Blob([media.data], { type: media.mime });return URL.createObjectURL(blob);} catch (e) {return null;}}return null;}function formatSize(bytes) {if (bytes < 1024) return bytes + 'B';if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + 'KB';return (bytes / (1024 * 1024)).toFixed(1) + 'MB';}// ----- 样式 -----GM_addStyle(`#ug-bg-layer {position: fixed;top: 0; left: 0;width: 100vw; height: 100vh;z-index: 0 !important;pointer-events: none !important;overflow: hidden;background: transparent !important;}#ug-bg-layer .ug-bg-media {position: absolute;top: 0; left: 0;width: 100%; height: 100%;object-fit: cover;transition: opacity 0.4s ease, filter 0.4s ease;opacity: 0;transform: translateZ(0);will-change: opacity, filter;}#ug-bg-layer .ug-bg-media.active {opacity: 1;}#ug-bg-layer video, #ug-bg-layer img {width: 100%; height: 100%;object-fit: cover;position: absolute;top: 0; left: 0;}#ug-bg-panel {position: fixed;z-index: 9999999;top: 100px;left: 100px;width: 320px;max-height: 80vh;overflow-y: auto;background: rgba(30,30,46,0.95);backdrop-filter: blur(20px);border-radius: 16px;padding: 16px;color: #eee;font-family: -apple-system, sans-serif;font-size: 13px;border: 1px solid rgba(255,255,255,0.08);box-shadow: 0 12px 48px rgba(0,0,0,0.5);transition: opacity 0.25s;}#ug-bg-panel.collapsed {opacity: 0;pointer-events: none;display: none;}#ug-bg-panel .row { display: flex; gap: 6px; margin: 6px 0; flex-wrap: wrap; align-items: center; }#ug-bg-panel .btn {padding: 6px 12px;border: none;border-radius: 6px;font-size: 12px;font-weight: 600;cursor: pointer;transition: 0.2s;}#ug-bg-panel .btn-primary { background: #6c5ce7; color: #fff; }#ug-bg-panel .btn-primary:hover { background: #5a4bd1; }#ug-bg-panel .btn-secondary { background: rgba(255,255,255,0.1); color: #ccc; }#ug-bg-panel .btn-secondary:hover { background: rgba(255,255,255,0.2); }#ug-bg-panel .btn-danger { background: #e74c3c; color: #fff; }#ug-bg-panel .btn-danger:hover { background: #c0392b; }#ug-bg-panel .btn-sm { padding: 4px 8px; font-size: 11px; }#ug-bg-panel .btn-success { background: #2ecc71; color: #fff; }#ug-bg-panel .btn-success:hover { background: #27ae60; }#ug-bg-panel .media-list { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; }#ug-bg-panel .media-item {position: relative;width: 50px; height: 50px;border-radius: 6px;border: 2px solid transparent;cursor: pointer;overflow: hidden;background: #222;}#ug-bg-panel .media-item.active { border-color: #6c5ce7; }#ug-bg-panel .media-item img, #ug-bg-panel .media-item video {width: 100%; height: 100%;object-fit: cover;}#ug-bg-panel .media-item .del {position: absolute;top: 0; right: 0;background: rgba(231,76,60,0.8);color: #fff;border: none;width: 16px; height: 16px;font-size: 10px;cursor: pointer;border-radius: 0 6px 0 6px;}#ug-bg-panel .hint { font-size: 11px; color: #666; margin-top: 4px; }#ug-bg-panel .slider-group {display: flex;align-items: center;gap: 10px;margin: 6px 0;}#ug-bg-panel .slider-group label {min-width: 50px;font-size: 12px;color: #aaa;text-align: right;}#ug-bg-panel .slider-group input[type="range"] {flex: 1;-webkit-appearance: none;height: 4px;border-radius: 2px;background: rgba(255,255,255,0.15);outline: none;}#ug-bg-panel .slider-group input[type="range"]::-webkit-slider-thumb {-webkit-appearance: none;width: 16px; height: 16px;border-radius: 50%;background: #6c5ce7;border: 2px solid #fff;cursor: pointer;}#ug-bg-panel .slider-group input[type="range"]::-moz-range-thumb {width: 16px; height: 16px;border-radius: 50%;background: #6c5ce7;border: 2px solid #fff;cursor: pointer;}#ug-bg-panel .val-display {min-width: 36px;text-align: center;font-size: 11px;font-weight: 600;color: #a29bfe;background: rgba(108,92,231,0.15);padding: 2px 6px;border-radius: 4px;}#ug-bg-panel .auto-input {width: 40px;background: #222;color: #fff;border: 1px solid #555;border-radius: 4px;padding: 2px 4px;text-align: center;font-size: 12px;}#ug-bg-panel .auto-input:focus {outline: none;border-color: #6c5ce7;}#ug-bg-panel .auto-status {font-size: 11px;color: #888;margin-top: 4px;}#ug-bg-panel .url-input {flex: 1;min-width: 180px;padding: 6px 10px;background: #222;color: #eee;border: 1px solid #555;border-radius: 6px;font-size: 12px;}#ug-bg-panel .url-input:focus {outline: none;border-color: #6c5ce7;}#ug-bg-toggle-btn {position: fixed;bottom: 30px;right: 30px;z-index: 9999998;width: 48px; height: 48px;border-radius: 50%;background: rgba(30,30,46,0.85);backdrop-filter: blur(12px);border: 1px solid rgba(255,255,255,0.1);color: #fff;font-size: 20px;cursor: grab;box-shadow: 0 4px 20px rgba(0,0,0,0.3);display: flex;align-items: center;justify-content: center;transition: background 0.2s;user-select: none;touch-action: none;}#ug-bg-toggle-btn:hover { background: rgba(108,92,231,0.85); }#ug-bg-toggle-btn:active { cursor: grabbing; }#ug-bg-toast {position: fixed;bottom: 90px;right: 90px;z-index: 9999999;background: rgba(0,0,0,0.8);color: #fff;padding: 8px 16px;border-radius: 8px;font-size: 13px;opacity: 0;transition: opacity 0.3s;pointer-events: none;}#ug-bg-toast.show { opacity: 1; }/* 帮助弹窗 */#ug-help-modal {position: fixed;top: 0; left: 0;width: 100vw; height: 100vh;background: rgba(0,0,0,0.6);z-index: 10000000;display: flex;align-items: center;justify-content: center;}#ug-help-content {background: #2a2a3e;color: #eee;padding: 20px;border-radius: 12px;width: 320px;max-width: 90vw;max-height: 90vh;overflow-y: auto;font-size: 13px;line-height: 1.6;border: 1px solid #444;box-shadow: 0 10px 40px rgba(0,0,0,0.5);}#ug-help-content h3 { margin-top: 0; color: #6c5ce7; }#ug-help-content p { margin: 8px 0; }#ug-help-content .close-help { margin-top: 15px; width: 100%; padding: 8px; background: #6c5ce7; color: #fff; border: none; border-radius: 6px; cursor: pointer; }/* 广告区域 */.ug-ad-section {border-top: 1px solid #444;margin-top: 15px;padding-top: 15px;text-align: center;}.ug-ad-text {font-size: 12px;color: #a29bfe;margin-bottom: 8px;font-weight: bold;}.ug-ad-img {width: 100%;border-radius: 8px;object-fit: cover;border: 1px solid #555;}`);// ----- Toast -----function showToast(msg, duration = 2000) {let t = document.getElementById('ug-bg-toast');if (!t) {t = document.createElement('div');t.id = 'ug-bg-toast';document.body.appendChild(t);}t.textContent = msg;t.classList.add('show');clearTimeout(t._timer);t._timer = setTimeout(() => t.classList.remove('show'), duration);}// ===== 状态管理 =====function loadState() {try {const raw = localStorage.getItem('ug_bg_state');if (raw) {const parsed = JSON.parse(raw);if (parsed.opacity === undefined || parsed.opacity === null) parsed.opacity = DEFAULT_OPACITY;if (parsed.blur === undefined || parsed.blur === null) parsed.blur = DEFAULT_BLUR;if (parsed.brightness === undefined || parsed.brightness === null) parsed.brightness = DEFAULT_BRIGHTNESS;if (parsed.zIndex === undefined || parsed.zIndex === null) parsed.zIndex = DEFAULT_Z_INDEX;if (parsed.autoSwitch === undefined || parsed.autoSwitch === null) parsed.autoSwitch = DEFAULT_AUTO_SWITCH;if (parsed.intervalHours === undefined || parsed.intervalHours === null) parsed.intervalHours = DEFAULT_INTERVAL_HOURS;if (parsed.intervalMinutes === undefined || parsed.intervalMinutes === null) parsed.intervalMinutes = DEFAULT_INTERVAL_MINUTES;if (parsed.intervalSeconds === undefined || parsed.intervalSeconds === null) parsed.intervalSeconds = DEFAULT_INTERVAL_SECONDS;return parsed;}} catch (e) {}return {selectedId: null,opacity: DEFAULT_OPACITY,blur: DEFAULT_BLUR,brightness: DEFAULT_BRIGHTNESS,zIndex: DEFAULT_Z_INDEX,autoSwitch: DEFAULT_AUTO_SWITCH,intervalHours: DEFAULT_INTERVAL_HOURS,intervalMinutes: DEFAULT_INTERVAL_MINUTES,intervalSeconds: DEFAULT_INTERVAL_SECONDS};}function saveState(state) {localStorage.setItem('ug_bg_state', JSON.stringify(state));}// ===== 应用层级 =====function applyZIndex(zIndex) {const layer = document.getElementById('ug-bg-layer');if (layer) {layer.style.setProperty('z-index', String(zIndex), 'important');}}// ===== 队列式切换核心逻辑 =====let switchQueue = [];let isSwitching = false;function renderBg(media) {if (switchQueue.length >= 5) {switchQueue.shift();}switchQueue.push(media);processQueue();}async function processQueue() {if (isSwitching || switchQueue.length === 0) return;isSwitching = true;const media = switchQueue.shift();try {await executeBackgroundChange(media);} catch (e) {console.error('[背景] 切换异常:', e);} finally {isSwitching = false;if (switchQueue.length > 0) {processQueue();}}}async function executeBackgroundChange(media) {const layer = document.getElementById('ug-bg-layer');if (!layer) {const newLayer = document.createElement('div');newLayer.id = 'ug-bg-layer';document.body.prepend(newLayer);return executeBackgroundChange(media);}if (!media) {layer.innerHTML = '';resetAutoTimer();return;}const state = loadState();const currentOpacity = state.opacity !== undefined ? state.opacity : DEFAULT_OPACITY;const currentZIndex = state.zIndex !== undefined ? state.zIndex : DEFAULT_Z_INDEX;const currentBlur = state.blur || 0;const currentBrightness = state.brightness || 100;layer.style.position = 'fixed';layer.style.top = '0';layer.style.left = '0';layer.style.width = '100vw';layer.style.height = '100vh';layer.style.overflow = 'hidden';layer.style.display = 'block';layer.style.background = 'transparent';layer.style.setProperty('z-index', String(currentZIndex), 'important');layer.style.setProperty('pointer-events', 'none', 'important');layer.style.setProperty('opacity', String(currentOpacity), 'important');let url;let isRemote = false;if (media.type === 'remote') {const sep = media.data.includes('?') ? '&' : '?';url = media.data + sep + '_t=' + Date.now();isRemote = true;} else {url = mediaToUrl(media);if (!url) {showToast('❌ 生成URL失败,请检查文件格式');return;}}const oldActiveEl = layer.querySelector('.ug-bg-media.active');if (oldActiveEl) {oldActiveEl.classList.remove('active');oldActiveEl.style.filter = `blur(30px) brightness(${currentBrightness / 100})`;oldActiveEl.style.opacity = '0';}let newEl;if (media.type === 'video') {newEl = document.createElement('video');newEl.src = url;newEl.muted = true;newEl.loop = true;newEl.playsInline = true;newEl.addEventListener('loadeddata', () => {newEl.play().catch(() => {});});newEl.onerror = () => {showToast('❌ 视频加载失败');if (newEl.parentNode) newEl.remove();};} else {newEl = document.createElement('img');if (isRemote) newEl.referrerPolicy = 'no-referrer';newEl.src = url;newEl.onerror = () => {showToast('❌ 图片加载失败,可能防盗链');if (newEl.parentNode) newEl.remove();};}newEl.className = 'ug-bg-media';newEl.style.transition = 'none';newEl.style.filter = `blur(30px) brightness(${currentBrightness / 100})`;newEl.style.opacity = '0';layer.appendChild(newEl);await new Promise((resolve) => {if (media.type === 'video') {if (newEl.readyState >= 2) return resolve();newEl.addEventListener('loadeddata', resolve, { once: true });} else {if (newEl.complete && newEl.naturalWidth > 0) return resolve();newEl.addEventListener('load', resolve, { once: true });}setTimeout(resolve, 3000);});void newEl.offsetWidth;newEl.style.transition = '';newEl.classList.add('active');newEl.style.opacity = '1';if (oldActiveEl) {setTimeout(() => {if (oldActiveEl.parentNode) oldActiveEl.remove();}, 450);}if (media.type === 'video') {newEl.play().catch(() => {});}setTimeout(() => {newEl.style.filter = `blur(${currentBlur}px) brightness(${currentBrightness / 100})`;}, 50);resetAutoTimer();}// ===== 自动切换相关 =====let switchTimer = null;async function switchToNextBg() {const all = await dbGetAll();if (all.length === 0) {showToast('⚠️ 无媒体可切换');return;}const state = loadState();let currentId = state.selectedId;if (!currentId || !all.some(m => m.id === currentId)) {currentId = all[0].id;} else {const index = all.findIndex(m => m.id === currentId);const nextIndex = (index + 1) % all.length;currentId = all[nextIndex].id;}const media = all.find(m => m.id === currentId);if (media) {state.selectedId = currentId;saveState(state);renderBg(media);const p = document.getElementById('ug-bg-panel');if (p && !p.classList.contains('collapsed')) {await showPanel(state);}}}function startAutoSwitch() {stopAutoSwitch();const state = loadState();const hours = parseInt(state.intervalHours) || 0;const minutes = parseInt(state.intervalMinutes) || 0;const seconds = parseInt(state.intervalSeconds) || 0;const totalMs = (hours * 3600 + minutes * 60 + seconds) * 1000;if (totalMs < 1000) {showToast('⚠️ 间隔时间至少 1 秒');return;}state.autoSwitch = true;saveState(state);switchTimer = setInterval(switchToNextBg, totalMs);updateAutoStatus(true, totalMs);showToast(`✅ 自动切换已启动`);}function stopAutoSwitch() {if (switchTimer) {clearInterval(switchTimer);switchTimer = null;}const state = loadState();state.autoSwitch = false;saveState(state);updateAutoStatus(false, 0);showToast('⏹️ 自动切换已停止');}function resetAutoTimer() {const state = loadState();if (state.autoSwitch) {if (switchTimer) {clearInterval(switchTimer);switchTimer = null;}const hours = parseInt(state.intervalHours) || 0;const minutes = parseInt(state.intervalMinutes) || 0;const seconds = parseInt(state.intervalSeconds) || 0;const totalMs = (hours * 3600 + minutes * 60 + seconds) * 1000;if (totalMs >= 1000) {state.autoSwitch = true;saveState(state);switchTimer = setInterval(switchToNextBg, totalMs);updateAutoStatus(true, totalMs);} else {state.autoSwitch = false;saveState(state);updateAutoStatus(false, 0);}}}function updateAutoStatus(isRunning, intervalMs) {const statusEl = document.getElementById('ug-auto-status');if (statusEl) {if (isRunning) {const sec = Math.floor(intervalMs / 1000);const h = Math.floor(sec / 3600);const m = Math.floor((sec % 3600) / 60);const s = sec % 60;statusEl.textContent = `✅ 运行中 (间隔 ${h}h ${m}m ${s}s)`;statusEl.style.color = '#2ecc71';} else {statusEl.textContent = '⏹️ 已停止';statusEl.style.color = '#888';}}}// ===== 面板位置跟随按钮 =====function updatePanelPosition() {const p = document.getElementById('ug-bg-panel');const btn = document.getElementById('ug-bg-toggle-btn');if (!p || !btn) return;if (p.classList.contains('collapsed')) return;const btnRect = btn.getBoundingClientRect();const panelW = p.offsetWidth || 320;const panelH = p.offsetHeight || 400;const gap = 12;const margin = 10;let left;if (btnRect.left - gap - panelW >= margin) {left = btnRect.left - gap - panelW;} else if (btnRect.right + gap + panelW <= window.innerWidth - margin) {left = btnRect.right + gap;} else {left = Math.max(margin, Math.min(window.innerWidth - panelW - margin, btnRect.left + btnRect.width / 2 - panelW / 2));}let top = btnRect.bottom - panelH;if (top < margin) top = margin;if (top + panelH > window.innerHeight - margin) {top = window.innerHeight - panelH - margin;}p.style.left = left + 'px';p.style.top = top + 'px';p.style.right = 'auto';p.style.bottom = 'auto';}// ===== 可拖动按钮 =====function createToggleButton() {if (document.getElementById('ug-bg-toggle-btn')) return;if (!document.body) {setTimeout(createToggleButton, 100);return;}const btn = document.createElement('div');btn.id = 'ug-bg-toggle-btn';btn.textContent = '🎨';try {const pos = JSON.parse(localStorage.getItem(BTN_POS_KEY) || 'null');if (pos && typeof pos.left === 'number' && typeof pos.top === 'number') {const maxLeft = Math.max(0, window.innerWidth - 48);const maxTop = Math.max(0, window.innerHeight - 48);const left = Math.min(Math.max(0, pos.left), maxLeft);const top = Math.min(Math.max(0, pos.top), maxTop);btn.style.left = left + 'px';btn.style.top = top + 'px';btn.style.right = 'auto';btn.style.bottom = 'auto';}} catch (e) {}let isDragging = false;let hasMoved = false;let startX = 0, startY = 0, startLeft = 0, startTop = 0;btn.addEventListener('pointerdown', (e) => {if (e.button !== 0 && e.pointerType === 'mouse') return;isDragging = true;hasMoved = false;startX = e.clientX;startY = e.clientY;const rect = btn.getBoundingClientRect();startLeft = rect.left;startTop = rect.top;try { btn.setPointerCapture(e.pointerId); } catch (err) {}e.preventDefault();});btn.addEventListener('pointermove', (e) => {if (!isDragging) return;const dx = e.clientX - startX;const dy = e.clientY - startY;if (!hasMoved && (Math.abs(dx) > 3 || Math.abs(dy) > 3)) {hasMoved = true;}if (!hasMoved) return;const w = btn.offsetWidth || 48;const h = btn.offsetHeight || 48;const newLeft = Math.max(0, Math.min(window.innerWidth - w, startLeft + dx));const newTop = Math.max(0, Math.min(window.innerHeight - h, startTop + dy));btn.style.left = newLeft + 'px';btn.style.top = newTop + 'px';btn.style.right = 'auto';btn.style.bottom = 'auto';// 实时更新面板位置updatePanelPosition();});const endDrag = (e) => {if (!isDragging) return;isDragging = false;try { btn.releasePointerCapture(e.pointerId); } catch (err) {}if (hasMoved) {const left = parseInt(btn.style.left, 10) || 0;const top = parseInt(btn.style.top, 10) || 0;localStorage.setItem(BTN_POS_KEY, JSON.stringify({ left, top }));updatePanelPosition();}};btn.addEventListener('pointerup', endDrag);btn.addEventListener('pointercancel', endDrag);btn.addEventListener('click', (e) => {if (hasMoved) {e.stopPropagation();e.preventDefault();hasMoved = false;return;}togglePanel();});document.body.appendChild(btn);}// ===== 面板 =====let panelVisible = false;let panel = null;async function togglePanel() {const state = loadState();panelVisible = !panelVisible;if (panelVisible) {await showPanel(state);} else {const p = document.getElementById('ug-bg-panel');if (p) p.classList.add('collapsed');}}// 显示帮助与广告function showHelp() {if (document.getElementById('ug-help-modal')) return;const modal = document.createElement('div');modal.id = 'ug-help-modal';modal.innerHTML = `<div id="ug-help-content"><h3>🎨 通用背景 帮助</h3><p><strong>📷 图片/🎬 视频:</strong>上传本地媒体文件,将直接作为背景。</p><p><strong>🌐 添加随机:</strong>填入图床直链(如 <code>https://img.moehu.org/pic.php?id=mrfz</code>),每次切换时都会重新抓取最新的随机图。</p><p><strong>模糊/亮度/透明度:</strong>实时调整当前背景的显示效果。</p><p><strong>层级:</strong>如果背景挡住了网页的文字,请调低层级;如果背景被网页原有的白底挡住,请调高。</p><p><strong>自动切换:</strong>设置时间后点“启动”,时间必须≥1秒,不支持负数。</p><div class="ug-ad-section"><div class="ug-ad-text">如果你也是明日方舟或者终末地玩家,可以在洛谷上找作者私信加好友哦。</div><div style="font-size:12px;color:#ccc;margin-bottom:8px;">ID:1486819<br>QQ:3339800393</div><img src="https://cdn.luogu.com.cn/upload/image_hosting/ycd3kzfw.webp" class="ug-ad-img" referrerPolicy="no-referrer" alt="作者名片"></div><button class="close-help" id="ug-help-close">我知道了</button></div>`;document.body.appendChild(modal);modal.querySelector('#ug-help-close').addEventListener('click', () => {modal.remove();});modal.addEventListener('click', (e) => {if (e.target === modal) modal.remove();});}async function showPanel(state) {if (!panel) {panel = document.createElement('div');panel.id = 'ug-bg-panel';document.body.appendChild(panel);}panel.classList.remove('collapsed');const all = await dbGetAll();let listHtml = '';if (all.length === 0) {listHtml = '<span style="color:#666;font-size:12px;">暂无媒体</span>';} else {listHtml = all.map(m => {const active = m.id === state.selectedId ? 'active' : '';if (m.type === 'remote') {return `<div class="media-item ${active}" data-id="${m.id}" title="随机图床: ${m.data}" style="background:#2a2a3e;display:flex;align-items:center;justify-content:center;font-size:22px;">🌐<button class="del" data-id="${m.id}">×</button></div>`;}const url = mediaToUrl(m);if (!url) return `<div class="media-item" style="border-color:red;">⚠️</div>`;return `<div class="media-item ${active}" data-id="${m.id}">${m.type === 'image' ? `<img src="${url}">` : `<video src="${url}" muted></video>`}<button class="del" data-id="${m.id}">×</button></div>`;}).join('');}const currentOpacity = state.opacity !== undefined ? state.opacity : DEFAULT_OPACITY;const currentBlur = state.blur !== undefined ? state.blur : DEFAULT_BLUR;const currentBrightness = state.brightness !== undefined ? state.brightness : DEFAULT_BRIGHTNESS;const currentZIndex = state.zIndex !== undefined ? state.zIndex : DEFAULT_Z_INDEX;const autoSwitch = state.autoSwitch || false;const h = state.intervalHours || 0;const m = state.intervalMinutes || 0;const s = state.intervalSeconds || 10;panel.innerHTML = `<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;"><span style="font-weight:700;font-size:15px;">🎨 背景设置</span><div style="display:flex;gap:6px;"><button class="btn btn-secondary btn-sm" id="ug-help-btn">?</button><button class="btn btn-secondary btn-sm" id="ug-panel-close">✕</button></div></div><div class="row"><button class="btn btn-primary btn-sm" id="ug-upload-img">📷 图片</button><button class="btn btn-primary btn-sm" id="ug-upload-video">🎬 视频</button><button class="btn btn-success btn-sm" id="ug-test-video">🎬 测试</button><button class="btn btn-danger btn-sm" id="ug-clear-all">清空</button></div><div class="hint">支持一次多选图片 · 单张 ≤ 25MB · 点击页面播放视频 · 默认透明度 0.1</div><div style="margin-top:8px;display:flex;gap:6px;align-items:center;flex-wrap:wrap;"><input type="text" id="ug-remote-input" placeholder="图床" class="url-input"><button class="btn btn-success btn-sm" id="ug-remote-add">🌐 添加随机</button></div><div class="hint"></div><div style="margin:10px 0;"><div class="slider-group"><label>模糊</label><input type="range" id="ug-slider-blur" min="0" max="30" value="${currentBlur}" step="1"><span class="val-display" id="ug-val-blur">${currentBlur}px</span></div><div class="slider-group"><label>亮度</label><input type="range" id="ug-slider-brightness" min="10" max="200" value="${currentBrightness}" step="5"><span class="val-display" id="ug-val-brightness">${currentBrightness}%</span></div><div class="slider-group"><label>透明度</label><input type="range" id="ug-slider-opacity" min="0" max="100" value="${Math.round(currentOpacity * 100)}" step="5"><span class="val-display" id="ug-val-opacity">${Math.round(currentOpacity * 100)}%</span></div><div class="slider-group"><label>层级</label><input type="range" id="ug-slider-zindex" min="-10" max="50" value="${currentZIndex}" step="1"><span class="val-display" id="ug-val-zindex">${currentZIndex}</span></div></div><div style="margin-top:10px;border-top:1px solid #444;padding-top:10px;"><div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;"><span style="font-size:12px;color:#aaa;">自动切换</span><input type="number" id="ug-auto-hours" min="0" max="23" value="${h}" class="auto-input">时<input type="number" id="ug-auto-minutes" min="0" max="59" value="${m}" class="auto-input">分<input type="number" id="ug-auto-seconds" min="0" max="59" value="${s}" class="auto-input">秒<button class="btn btn-primary btn-sm" id="ug-auto-start">▶ 启动</button><button class="btn btn-danger btn-sm" id="ug-auto-stop">⏹ 停止</button></div><div id="ug-auto-status" class="auto-status">${autoSwitch ? '✅ 运行中' : '⏹️ 已停止'}</div></div><div style="margin-top:10px;"><div style="font-size:12px;color:#888;">已保存 (${all.length})</div><div class="media-list">${listHtml}</div></div><div style="margin-top:12px;font-size:11px;color:#555;text-align:center;">点击缩略图切换背景</div>`;requestAnimationFrame(updatePanelPosition);panel.querySelector('#ug-panel-close').addEventListener('click', togglePanel);panel.querySelector('#ug-help-btn').addEventListener('click', showHelp);// 批量上传图片:文件选择器支持多选,保存完成后只刷新一次面板。panel.querySelector('#ug-upload-img').addEventListener('click', () => {const inp = document.createElement('input');inp.type = 'file';inp.accept = 'image/*';inp.multiple = true;inp.onchange = async e => {const selected = Array.from(e.target.files || []);if (selected.length === 0) return;const validFiles = [];const rejected = [];for (const file of selected) {if (!file.type || !file.type.startsWith('image/')) {rejected.push(`${file.name}(不是图片)`);} else if (file.size > MAX_SIZE) {rejected.push(`${file.name}(${formatSize(file.size)},超过 25MB)`);} else {validFiles.push(file);}}if (validFiles.length === 0) {showToast(`❌ 没有可上传的图片(已跳过 ${rejected.length} 个文件)`, 3500);return;}const uploadBtn = panel.querySelector('#ug-upload-img');if (uploadBtn) {uploadBtn.disabled = true;uploadBtn.textContent = `⏳ 保存中 0/${validFiles.length}`;}try {// IndexedDB 可直接保存 Blob,无需逐张 FileReader 转 Base64。const ids = await dbSaveMany(validFiles.map(file => ({data: file,type: 'image',mime: file.type})));const state = loadState();const lastId = ids[ids.length - 1];state.selectedId = lastId;saveState(state);const all = await dbGetAll();const media = all.find(m => m.id === lastId);if (media) renderBg(media);await showPanel(state);let message = `✅ 已批量保存 ${ids.length} 张图片`;if (rejected.length) message += `,跳过 ${rejected.length} 个文件`;showToast(message, 3500);if (rejected.length) {console.warn('[背景脚本] 以下文件未上传:', rejected);}} catch (err) {console.error('[背景脚本] 批量图片保存失败:', err);showToast('❌ 批量图片保存失败: ' + (err.message || err), 4000);await showPanel(loadState());} finally {const currentBtn = document.querySelector('#ug-upload-img');if (currentBtn) {currentBtn.disabled = false;currentBtn.textContent = '📷 图片';}}};inp.click();});// 上传视频panel.querySelector('#ug-upload-video').addEventListener('click', () => {const inp = document.createElement('input');inp.type = 'file';inp.accept = 'video/mp4,video/webm,video/*';inp.onchange = async e => {const f = e.target.files[0];if (!f) return;if (f.size > MAX_SIZE) {alert(`文件 ${formatSize(f.size)} 超过 25MB`);return;}try {const buf = await blobToArrayBuffer(f);const id = await dbSave(buf, 'video', f.type);const state = loadState();state.selectedId = id;saveState(state);const all = await dbGetAll();const media = all.find(m => m.id === id);renderBg(media);await showPanel(state);showToast('✅ 视频已保存');} catch (err) {showToast('❌ 视频保存失败: ' + err.message);}};inp.click();});// 测试视频 (换用 W3C 官方源,极大提升连通率)panel.querySelector('#ug-test-video').addEventListener('click', async () => {try {const testUrl = 'https://media.w3.org/2010/05/sintel/trailer.mp4';const resp = await fetch(testUrl);if (!resp.ok) throw new Error('网络错误');const blob = await resp.blob();if (!blob.type.startsWith('video/')) throw new Error('不是视频格式');const buf = await blobToArrayBuffer(blob);const id = await dbSave(buf, 'video', blob.type);const state = loadState();state.selectedId = id;saveState(state);const all = await dbGetAll();const media = all.find(m => m.id === id);renderBg(media);await showPanel(state);showToast('✅ 测试视频已加载');} catch (err) {showToast('❌ 测试视频失败: ' + err.message);}});// 添加图床链panel.querySelector('#ug-remote-add').addEventListener('click', async () => {const input = panel.querySelector('#ug-remote-input');const rawUrl = (input.value || '').trim();if (!rawUrl) { showToast('⚠️ 请输入 URL'); return; }if (!/^https?:\/\//i.test(rawUrl)) { showToast('⚠️ URL 必须以 http(s):// 开头'); return; }try {const id = await dbSave(rawUrl, 'remote', 'image/*');const state = loadState();state.selectedId = id;saveState(state);const all = await dbGetAll();const media = all.find(m => m.id === id);renderBg(media);input.value = '';await showPanel(state);showToast('✅ 随机图床已添加');} catch (err) {showToast('❌ 保存失败: ' + err.message);}});// 清空panel.querySelector('#ug-clear-all').addEventListener('click', async () => {if (confirm('清空所有背景?')) {await dbClear();const state = loadState();state.selectedId = null;saveState(state);renderBg(null);await showPanel(state);showToast('已清空');if (state.autoSwitch) stopAutoSwitch();}});// 点击缩略图panel.querySelectorAll('.media-item').forEach(el => {el.addEventListener('click', async e => {if (e.target.closest('.del')) return;const id = Number(el.dataset.id);const all = await dbGetAll();const media = all.find(m => m.id === id);if (media) {const state = loadState();state.selectedId = id;saveState(state);renderBg(media);await showPanel(state);}});});// 删除panel.querySelectorAll('.del').forEach(el => {el.addEventListener('click', async e => {e.stopPropagation();const id = Number(el.dataset.id);await dbDelete(id);const state = loadState();if (state.selectedId === id) {state.selectedId = null;saveState(state);renderBg(null);}await showPanel(state);});});// 透明度滑块const opacitySlider = panel.querySelector('#ug-slider-opacity');const opacityDisplay = panel.querySelector('#ug-val-opacity');opacitySlider.addEventListener('input', () => {const val = parseInt(opacitySlider.value) / 100;opacityDisplay.textContent = Math.round(val * 100) + '%';const layer = document.getElementById('ug-bg-layer');if (layer) {layer.style.setProperty('opacity', String(val), 'important');}const state = loadState();state.opacity = val;saveState(state);});// 模糊滑块const blurSlider = panel.querySelector('#ug-slider-blur');const blurDisplay = panel.querySelector('#ug-val-blur');blurSlider.addEventListener('input', () => {const val = parseInt(blurSlider.value);blurDisplay.textContent = val + 'px';const state = loadState();state.blur = val;saveState(state);const layer = document.getElementById('ug-bg-layer');const activeEls = layer ? layer.querySelectorAll('.ug-bg-media.active') : [];activeEls.forEach(el => {el.style.filter = `blur(${val}px) brightness(${state.brightness / 100})`;});});// 亮度滑块const brightSlider = panel.querySelector('#ug-slider-brightness');const brightDisplay = panel.querySelector('#ug-val-brightness');brightSlider.addEventListener('input', () => {const val = parseInt(brightSlider.value);brightDisplay.textContent = val + '%';const state = loadState();state.brightness = val;saveState(state);const layer = document.getElementById('ug-bg-layer');const activeEls = layer ? layer.querySelectorAll('.ug-bg-media.active') : [];activeEls.forEach(el => {el.style.filter = `blur(${state.blur}px) brightness(${val / 100})`;});});// 层级滑块const zIndexSlider = panel.querySelector('#ug-slider-zindex');const zIndexDisplay = panel.querySelector('#ug-val-zindex');zIndexSlider.addEventListener('input', () => {const val = parseInt(zIndexSlider.value);zIndexDisplay.textContent = val;const state = loadState();state.zIndex = val;saveState(state);applyZIndex(val);});// 自动切换const autoStartBtn = panel.querySelector('#ug-auto-start');const autoStopBtn = panel.querySelector('#ug-auto-stop');const hoursInput = panel.querySelector('#ug-auto-hours');const minutesInput = panel.querySelector('#ug-auto-minutes');const secondsInput = panel.querySelector('#ug-auto-seconds');autoStartBtn.addEventListener('click', () => {let hVal = parseInt(hoursInput.value) || 0;let mVal = parseInt(minutesInput.value) || 0;let sVal = parseInt(secondsInput.value) || 0;hVal = Math.max(0, Math.min(23, hVal));mVal = Math.max(0, Math.min(59, mVal));sVal = Math.max(0, Math.min(59, sVal));hoursInput.value = hVal;minutesInput.value = mVal;secondsInput.value = sVal;const state = loadState();state.intervalHours = hVal;state.intervalMinutes = mVal;state.intervalSeconds = sVal;saveState(state);startAutoSwitch();});autoStopBtn.addEventListener('click', stopAutoSwitch);if (state.autoSwitch) {const totalMs = ((state.intervalHours || 0) * 3600 + (state.intervalMinutes || 0) * 60 + (state.intervalSeconds || 0)) * 1000;updateAutoStatus(true, totalMs);}}// ===== 守护 =====let watchTimer = null;function startPatchWatcher() {if (watchTimer) clearInterval(watchTimer);const check = () => {if (!document.body) return;if (!document.getElementById('ug-bg-layer')) {const state = loadState();if (state.selectedId) {dbGetAll().then(all => {const media = all.find(m => m.id === state.selectedId);if (media && !document.getElementById('ug-bg-layer')) {renderBg(media);}});}}if (!document.getElementById('ug-bg-toggle-btn')) {createToggleButton();}};check();watchTimer = setInterval(check, 1500);}// ===== 窗口大小改变 =====let resizeRaf = null;window.addEventListener('resize', () => {if (resizeRaf) return;resizeRaf = requestAnimationFrame(() => {resizeRaf = null;updatePanelPosition();const btn = document.getElementById('ug-bg-toggle-btn');if (btn && btn.style.left) {const w = btn.offsetWidth || 48;const h = btn.offsetHeight || 48;const left = Math.min(parseInt(btn.style.left, 10) || 0, window.innerWidth - w);const top = Math.min(parseInt(btn.style.top, 10) || 0, window.innerHeight - h);btn.style.left = Math.max(0, left) + 'px';btn.style.top = Math.max(0, top) + 'px';}});});// ----- 初始化 -----async function init() {try {createToggleButton();const state = loadState();if (state.selectedId) {const all = await dbGetAll();const media = all.find(m => m.id === state.selectedId);if (media) {renderBg(media);} else {state.selectedId = null;saveState(state);}}startPatchWatcher();if (state.autoSwitch) {const totalMs = ((state.intervalHours || 0) * 3600 + (state.intervalMinutes || 0) * 60 + (state.intervalSeconds || 0)) * 1000;if (totalMs >= 1000) {startAutoSwitch();} else {state.autoSwitch = false;saveState(state);}}document.addEventListener('click', () => {const video = document.querySelector('#ug-bg-layer .ug-bg-media.active');if (video && video.paused && video.tagName === 'VIDEO') {video.play().catch(() => {});}}, { once: false });// 首次使用弹出说明和广告if (!localStorage.getItem(SEEN_AD_KEY)) {showHelp();localStorage.setItem(SEEN_AD_KEY, 'true');}console.log('[初始化] 🎨 通用背景 v1.4.0 已启动');} catch (e) {console.error('[初始化] 启动失败:', e);}}if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', init);} else {init();}})();```::::