版本比较
脚本——通用壁纸
正文
增加 1366 行删除 1175 行
123456782 行未改动111213141215161718192021222324252627142829303132333435363724253839404129424344454647484950515253545556573958594142436061626364656667686951707153545556577273747576775960616263646566787980818283848586686970718788899091737475767778798081828392939495969798991008586878889909192939495969710110210310410510610710810911011111211311411599100101102103104105106107108109110111112116117118119120121122123124125126127128129130114115116117118119120121122123131132133134135136137138139140141125126127128129130131132133134142143144145146147148149150136137138139140141142143144145151152153154155156157158159160161162163147148149150151152153154155156164165166167168169158159160161162163164165166170171172173174175176177178179180168169170171172173174175181182183184185186187188189190191177178179180181182183184185186187188189190191192193194195196197192193194195196197198199200201202199200201202203203204205206207208209210211212205206207208209210211212213214215216217218219220221222223224225226227228229230231232213214215216217218219220221234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303222223224225226227228229230231232233234235236237238239240241242243244245246305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349247248249250251252351352353354355356357358359360361362363364365366367368369253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283371372373374375376377378379380381382383384284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354386387388389390391392393394395396397398399400401402403404405406407408355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400410411412413414415416417418419420421422423424425401402403404405406407408409410411412413414415416417418419420427428429430431432433434435436437438439421422423424425426427428429430431432433434435441442443444445446447448449450451452453454455456457458459460461462463464465466467468469436437438439440441442443444445446447448449450451452453454455456457458459471472473460461462463464465466467468469470471472473474475475476477478479480481476477478479480481482483484485486487488489490491492493494495496497498499500501502503504483484485486487488489490491492505506507508509510511512513514515516517518519520521522523524525494495496497498499500501502503526527528529530531532533534535536537538539505506507508540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569510511512570571572573514515516517518519520521522523524574575576577578579580581526527528529530531532533534535536537538539582583584585541542543544545546547548549550551552553554555556557558559560561562563564565566567586587588589590591592593569570571572573594595596597575576598599600601602603604605606607608609610578579580581582583584585586587588589590591592593594595596597598599600601611612613614615616617618619603604605606607608609610611612613614615616617618619620621622623624625620621622623624625627628629630631632633634635636637638639640641642643644626627628629630631646647632633634635636637638639640641642643649650651652653654655656657658659660661662663664665666667668669670671672673674644645646647648649650651652653654655656657676677678679680681682683684685686687688689690691692658659660661662663664694695696697698699700701702703704665666667668669670671672673674675676677678679680681682683684685686687688706707708709710711712713714715716717718719720721722723724725726727728689690691692693730731732733734735736737738739740741742743744745694695747748749750751752696697698699700701702703704705706754755756757758707708709710711760761762763764765766767712713714715716717769770771772773718719720721775776777778779722723724725781782783784785786787726727728789790791729730731793794795796797798799800801802803804805732733734735736737738739740741742743744745746747748749750751752753754755756757758807808809759760761762763764765766767768769770771772773774775776811812813814815816817818819820821822777778779780781782783784785786787788824825826827828829830831832833834835836837838839840789790791792793794795796797798799800801802803804805806807808809810811812842843844845846847848849850851852813814815816817818819820821822823824825826827828829854855830831832833834835836857858859860861862863864865837838839840841842867868843844845846847848849850851870871872852853854855856857874875876877878879880881882883858859860861862863885886887888889890891864865866867868869870871893894895896897898899900901902903904905906907908909910911912913872873874875915916917918919920921922876877878879880881882883884885886887888889924925926927928890891892893930931932933934935936894895896897898899900901902903904905906938939940941942907908909910911912913914915916917918919920921922923944945946947948949950951952953954955956957958959960961962963964965924925926927967968969970971972973974975976977928929930931932933934935936937938939979980981982940941942984985943944945946947948949950951952987953954955989956957958959991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810199609619629639649659669679689699701021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104997197297397497597697797897998098198298398410511052105310541055105610571058105910601061106210631064106510661067106810691070107110729859869879889899901074107510761077107810799919929939949959969979989991000100110021081108210831084108510861087108810891090109110921093109410951003100410051006100710081009101010971098109911001101110211031104110511061107110811091011101210131014101510161017101810191020102110221023102410251026102710281029103010311032111111121113111411151116111711181119112011211122112311241125112610331034103510361037103810391040104111281129113011311132113311341135113611371138113911401141114210421043104410451046104710481049105011441145114611471148114911501151115211531154115511561157105110521053105410551056105710581159116011611162116311641165116611671168116911701171105910601061106210631064117311741175117611771178117911801181118211831184118510651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087118711881189119011911192119311941195119611971088108910901091109210931094109510961097109810991199120012011202120312041100110111021103110412061207120812091210121112121213110511061107121511081109121712181219122012211110111111121223122411131114111511161117111811191120112111221226122711231124112512291230123112321233123412351236123712381239124012411242124312441245112611271128112911301131113211331134113512471248124911361137113811391140125112521253125412551256125712581259126012611262126312641265126612671268114111421143114411451146127012711272127311471148114911501151115211531154127512761277127812791280128112821283128412851155115611571158115912871160116111621163128912901291129212931294129512961297116411651299130013011302130313041166116711681169130613071308130913101170117111721173117411751176117711781179118011811182118311841185118611871312131313141315131611881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510~~话说这玩意到底投哪个板块啊,投太多不会被封号吧qwq~~2026.11.27
效果展示(deepseek/atcoder/QQ浏览器-新标签页/洛谷部分页面)---2 行未改动
前言----首先,本脚本肯定使用了deepseek。无论是学习这个语言还是后期更改。并且似乎和洛谷不太适配。(但是后面作者发现只要自己新建一个主题然后去掉洛谷自带的背景就可以正常用了。——2026.8.3 21:32:50)[洛谷专用](https://www.luogu.com.cn/article/k0wlh572)首先,本脚本肯定使用了deepseek。无论是学习这个语言还是后期更改。并且似乎和洛谷不太适配。(但是后面作者发现只要自己新建一个主题然后去掉洛谷自带的背景就可以正常用了。——2026.8.3 21:32:50)[洛谷专用——他人](https://www.luogu.com.cn/article/k0wlh572)
如何使用---- 很显然,你需要一个tempermonkey。不过似乎有人不知道。 - 首先,点开右上角菜单,找到“扩展”/“插件”, - 点进去,找到“获取拓展”。 - 搜索tempermonkey,下载。 - 新建脚本,Ctrl+S保存。它就自动启动了。 - 如果不行的话,点击右上角拓展图标。 - 管理拓展。 - 找到tempermonkey的详细信息。 - 全部勾选。启动脚本后刷新网页。然后点击右下角的🎨按钮,点击图片/视频,就可以添加了。如果看不到图,就调一下层级,因为不同网站它文字的层级不同。甚至有的网站它文字框(有的甚至没有文字框)是和背景同一层级的,所以说,您的图片只能置顶了(调一下透明度就好啦)。- 启动脚本后刷新网页。然后点击右下角的🎨按钮,点击图片/视频,就可以添加了。如果看不到图,就调一下层级,因为不同网站它文字的层级不同。甚至有的网站它文字框(有的甚至没有文字框)是和背景同一层级的,所以说,您的图片只能置顶了(调一下透明度就好啦)。
小问题-----因为生成逻辑,在某些网站上它可能会出现重影一样的情况,甚至会出现多个按钮。这时,请您调一下层级。若依旧不行或者有多个按钮,请私信并告知网站。
目前已知问题网站 [QQ邮箱](mail.qq.com)
更新预告------ 更丝滑的背景转换。- 按钮的修复。- 暂无
更新日志----- 2026.2.26 OK,现在可以在洛谷上用了。但是bug好多(不太适配),还是建议找单独适用洛谷的脚本。如果硬要用这个,在黑名单里剔除就好。- 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 通用背景// @name 通用背景(pro)// @namespace https://www.luogu.com.cn/user/1486819// @version 1.2.1// @description 任何网站设置背景,支持上传/随机图床URL、手动/自动切换、平滑过渡、可拖动按钮// @author ArknightsEndfield// @version 1.4.0// @description 在大部分网站设置背景,支持批量上传图片、上传视频/图床URL、手动/自动切换、可拖动按钮// @author XiArk// @license MIT// @match *://*/*// @grant GM_addStyle// @run-at document-idle// ==/UserScript==
(function() { 'use strict'; 'use strict';
// ===== 黑名单 ===== const BLACKLIST = [ // 'luogu.com.cn', 'oier.baoshuo.dev', ]; // ===== 黑名单 ===== 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); }); 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; } 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; } // ===== 只在顶层窗口运行 ===== 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 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); }); } // ----- 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 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); }); } // 批量保存:所有图片共用一个 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;
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); }); } 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('写入失败'); }; }
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); }); } tx.oncomplete = () => resolve(ids); tx.onerror = () => reject(requestError || tx.error || new Error('批量保存失败')); tx.onabort = () => reject(requestError || tx.error || new Error('批量保存已中止')); }); }
// ----- 工具 ----- function blobToArrayBuffer(blob) { return new Promise((resolve, reject) => { const r = new FileReader(); r.onload = () => resolve(r.result); r.onerror = reject; r.readAsArrayBuffer(blob); }); } 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); }); }
function fileToDataURL(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = reject; reader.readAsDataURL(file); }); } 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); }); }
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; } 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 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'; } // ----- 工具 ----- function blobToArrayBuffer(blob) { return new Promise((resolve, reject) => { const r = new FileReader(); r.onload = () => resolve(r.result); r.onerror = reject; r.readAsArrayBuffer(blob); }); }
// ----- 样式 ----- 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; } function fileToDataURL(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = reject; reader.readAsDataURL(file); }); }
#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; } 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; }
#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; } 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'; }
#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; } // ----- 样式 ----- 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 .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-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-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-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-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-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; }
// ----- 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); } #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; }
// ===== 状态管理 ===== 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 }; } #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; }
function saveState(state) { localStorage.setItem('ug_bg_state', JSON.stringify(state)); } #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; }
// ===== 应用层级 ===== function applyZIndex(zIndex) { const layer = document.getElementById('ug-bg-layer'); if (layer) { layer.style.setProperty('z-index', String(zIndex), 'important'); } } /* 帮助弹窗 */ #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; }
// ===== 滤镜应用 ===== 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})`; } } /* 广告区域 */ .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; } `);
// ===== 渲染背景(支持 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; } // ----- 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); }
if (!media) { layer.innerHTML = ''; return; } // ===== 状态管理 ===== 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 }; }
const state = loadState(); const currentOpacity = state.opacity !== undefined ? state.opacity : DEFAULT_OPACITY; const currentZIndex = state.zIndex !== undefined ? state.zIndex : DEFAULT_Z_INDEX; function saveState(state) { localStorage.setItem('ug_bg_state', JSON.stringify(state)); }
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'); // ===== 应用层级 ===== function applyZIndex(zIndex) { const layer = document.getElementById('ug-bg-layer'); if (layer) { layer.style.setProperty('z-index', String(zIndex), '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 switchQueue = []; let isSwitching = false;
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(); }; } function renderBg(media) { if (switchQueue.length >= 5) { switchQueue.shift(); } switchQueue.push(media); processQueue(); }
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); async function processQueue() { if (isSwitching || switchQueue.length === 0) return; isSwitching = true;
let loadResolve = () => {}; const loadPromise = new Promise(resolve => { loadResolve = resolve; }); const media = switchQueue.shift(); try { await executeBackgroundChange(media); } catch (e) { console.error('[背景] 切换异常:', e); } finally { isSwitching = false; if (switchQueue.length > 0) { processQueue(); } } }
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(); }; } } 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); }
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(); }); if (!media) { layer.innerHTML = ''; resetAutoTimer(); return; }
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); } 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;
// ===== 自动切换相关 ===== let switchTimer = null; 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');
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); } } } 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; } }
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}秒)`); } 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'; }
function stopAutoSwitch() { if (switchTimer) { clearInterval(switchTimer); switchTimer = null; } const state = loadState(); state.autoSwitch = false; saveState(state); updateAutoStatus(false, 0); showToast('⏹️ 自动切换已停止'); } 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(); }; }
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); } } } newEl.className = 'ug-bg-media'; newEl.style.transition = 'none'; newEl.style.filter = `blur(30px) brightness(${currentBrightness / 100})`; newEl.style.opacity = '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'; } } } layer.appendChild(newEl);
// ===== 面板位置跟随按钮 ===== 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; 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); });
const btnRect = btn.getBoundingClientRect(); const panelW = p.offsetWidth || 320; const panelH = p.offsetHeight || 400; const gap = 12; const margin = 10; void newEl.offsetWidth; newEl.style.transition = ''; newEl.classList.add('active'); newEl.style.opacity = '1';
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)); } if (oldActiveEl) { setTimeout(() => { if (oldActiveEl.parentNode) oldActiveEl.remove(); }, 450); }
let top = btnRect.bottom - panelH; if (top < margin) top = margin; if (top + panelH > window.innerHeight - margin) { top = window.innerHeight - panelH - margin; } if (media.type === 'video') { newEl.play().catch(() => {}); }
p.style.left = left + 'px'; p.style.top = top + 'px'; p.style.right = 'auto'; p.style.bottom = 'auto'; } setTimeout(() => { newEl.style.filter = `blur(${currentBlur}px) brightness(${currentBrightness / 100})`; }, 50);
// ===== 可拖动按钮 ===== function createToggleButton() { if (document.getElementById('ug-bg-toggle-btn')) return; if (!document.body) { setTimeout(createToggleButton, 100); return; } resetAutoTimer(); }
const btn = document.createElement('div'); btn.id = 'ug-bg-toggle-btn'; btn.textContent = '🎨'; // ===== 自动切换相关 ===== let switchTimer = null;
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) {} 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); } } }
let isDragging = false; let hasMoved = false; let startX = 0, startY = 0, startLeft = 0, startTop = 0; 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(`✅ 自动切换已启动`); }
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(); }); function stopAutoSwitch() { if (switchTimer) { clearInterval(switchTimer); switchTimer = null; } const state = loadState(); state.autoSwitch = false; saveState(state); updateAutoStatus(false, 0); showToast('⏹️ 自动切换已停止'); }
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'; }); 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); } } }
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(); } }; 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'; } } }
btn.addEventListener('pointerup', endDrag); btn.addEventListener('pointercancel', endDrag); // ===== 面板位置跟随按钮 ===== 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;
btn.addEventListener('click', (e) => { if (hasMoved) { e.stopPropagation(); e.preventDefault(); hasMoved = false; return; } togglePanel(); }); const btnRect = btn.getBoundingClientRect(); const panelW = p.offsetWidth || 320; const panelH = p.offsetHeight || 400; const gap = 12; const margin = 10;
document.body.appendChild(btn); } 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 panelVisible = false; let panel = null; let top = btnRect.bottom - panelH; if (top < margin) top = margin; if (top + panelH > window.innerHeight - margin) { top = window.innerHeight - panelH - margin; }
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'); } } p.style.left = left + 'px'; p.style.top = top + 'px'; p.style.right = 'auto'; p.style.bottom = 'auto'; }
async function showPanel(state) { if (!panel) { panel = document.createElement('div'); panel.id = 'ug-bg-panel'; document.body.appendChild(panel); } panel.classList.remove('collapsed'); // ===== 可拖动按钮 ===== function createToggleButton() { if (document.getElementById('ug-bg-toggle-btn')) return; if (!document.body) { setTimeout(createToggleButton, 100); return; }
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 btn = document.createElement('div'); btn.id = 'ug-bg-toggle-btn'; btn.textContent = '🎨';
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; 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) {}
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> let isDragging = false; let hasMoved = false; let startX = 0, startY = 0, startLeft = 0, startTop = 0;
<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> 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(); });
<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> 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';
<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> // 实时更新面板位置 updatePanelPosition(); });
<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> 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(); } };
<div style="margin-top:10px;"> <div style="font-size:12px;color:#888;">已保存 (${all.length})</div> <div class="media-list">${listHtml}</div> </div> btn.addEventListener('pointerup', endDrag); btn.addEventListener('pointercancel', endDrag);
<div style="margin-top:12px;font-size:11px;color:#555;text-align:center;">点击缩略图切换背景</div> `; btn.addEventListener('click', (e) => { if (hasMoved) { e.stopPropagation(); e.preventDefault(); hasMoved = false; return; } togglePanel(); });
requestAnimationFrame(updatePanelPosition); document.body.appendChild(btn); }
panel.querySelector('#ug-panel-close').addEventListener('click', togglePanel); // ===== 面板 ===== let panelVisible = false; let panel = null;
// 上传图片 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(); }); 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'); } }
// 上传视频 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(); }); // 显示帮助与广告 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>
// 测试视频 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); } }); <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>
// 添加图床链(直接存 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; } <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(); }); }
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); } }); async function showPanel(state) { if (!panel) { panel = document.createElement('div'); panel.id = 'ug-bg-panel'; document.body.appendChild(panel); } panel.classList.remove('collapsed');
// 清空 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(); } }); 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(''); }
// 点击缩略图 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); } }); }); 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.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); }); }); 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>
// 透明度滑块 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); }); <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>
// 模糊滑块 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); }); <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>
// 亮度滑块 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); }); <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>
// 层级滑块 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); }); <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>
// 自动切换 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'); <div style="margin-top:10px;"> <div style="font-size:12px;color:#888;">已保存 (${all.length})</div> <div class="media-list">${listHtml}</div> </div>
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(); }); <div style="margin-top:12px;font-size:11px;color:#555;text-align:center;">点击缩略图切换背景</div> `;
autoStopBtn.addEventListener('click', stopAutoSwitch); requestAnimationFrame(updatePanelPosition);
if (state.autoSwitch) { const totalMs = ((state.intervalHours || 0) * 3600 + (state.intervalMinutes || 0) * 60 + (state.intervalSeconds || 0)) * 1000; updateAutoStatus(true, totalMs); } } panel.querySelector('#ug-panel-close').addEventListener('click', togglePanel); panel.querySelector('#ug-help-btn').addEventListener('click', showHelp);
// ===== 守护(setInterval 检查) ===== let watchTimer = null; // 批量上传图片:文件选择器支持多选,保存完成后只刷新一次面板。 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;
function startPatchWatcher() { if (watchTimer) clearInterval(watchTimer); const validFiles = []; const rejected = [];
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(); } }; 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); } }
check(); watchTimer = setInterval(check, 1500); } if (validFiles.length === 0) { showToast(`❌ 没有可上传的图片(已跳过 ${rejected.length} 个文件)`, 3500); return; }
// ===== 窗口大小改变 ===== 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'; } }); }); const uploadBtn = panel.querySelector('#ug-upload-img'); if (uploadBtn) { uploadBtn.disabled = true; uploadBtn.textContent = `⏳ 保存中 0/${validFiles.length}`; }
// ----- 初始化 ----- async function init() { try { createToggleButton(); try { // IndexedDB 可直接保存 Blob,无需逐张 FileReader 转 Base64。 const ids = await dbSaveMany(validFiles.map(file => ({ data: file, type: 'image', mime: file.type })));
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); } } const state = loadState(); const lastId = ids[ids.length - 1]; state.selectedId = lastId; saveState(state);
startPatchWatcher(); const all = await dbGetAll(); const media = all.find(m => m.id === lastId); if (media) renderBg(media);
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); } } await showPanel(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 }); let message = `✅ 已批量保存 ${ids.length} 张图片`; if (rejected.length) message += `,跳过 ${rejected.length} 个文件`; showToast(message, 3500);
console.log('[初始化] 🎨 通用背景 v1.2.1 已启动(remote 直接赋 URL)'); } catch (e) { console.error('[初始化] 启动失败:', e); } } 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(); });
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); } // 上传视频 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(); }
})();```
::::