话说这玩意到底投哪个板块啊,投太多不会被封号吧qwq2026.11.27
效果展示(deepseek/atcoder/QQ浏览器-新标签页/洛谷部分页面)
前言
首先,本脚本肯定使用了deepseek。无论是学习这个语言还是后期更改。并且似乎和洛谷不太适配。(但是后面作者发现只要自己新建一个主题然后去掉洛谷自带的背景就可以正常用了。——2026.8.3 21:32:50)洛谷专用——他人
如何使用
- 很显然,你需要一个tempermonkey。不过似乎有人不知道。
- 首先,点开右上角菜单,找到“扩展”/“插件”,
- 点进去,找到“获取拓展”。
- 搜索tempermonkey,下载。
- 新建脚本,Ctrl+S保存。它就自动启动了。
- 如果不行的话,点击右上角拓展图标。
- 管理拓展。
- 找到tempermonkey的详细信息。
- 全部勾选。
- 启动脚本后刷新网页。然后点击右下角的🎨按钮,点击图片/视频,就可以添加了。如果看不到图,就调一下层级,因为不同网站它文字的层级不同。甚至有的网站它文字框(有的甚至没有文字框)是和背景同一层级的,所以说,您的图片只能置顶了(调一下透明度就好啦)。
小问题
因为生成逻辑,在某些网站上它可能会出现重影一样的情况,甚至会出现多个按钮。这时,请您调一下层级。若依旧不行或者有多个按钮,请私信并告知网站。
目前已知问题网站 QQ邮箱
更新预告
- 暂无
更新日志
- 2026.2.26 OK,现在可以在洛谷上用了。但是bug好多(不太适配),还是建议找单独适用洛谷的脚本。如果硬要用这个,在黑名单里剔除就好。——已修。现在完全可以适配。
- 2026.2.27 将视频限制上调为25MB,支持定时更换背景。
- 2026.9.24 可以拖动的按钮,但是似乎有点问题???
- 2026.10.11 可以直接从一些网站的图床上传图片。不用再下载到本地。但是这会使得加载有点小慢,可能要好几秒。
- 2026.10.21
- 更丝滑的背景转换。
- 切换背景时的某些问题。
- 按钮的修复。
- 2026.11.27
- 可以一次性上传大量的图片,不用再一个一个上传了。然后给大家一个很好的图源。出门右转
脚本
有点长
// ==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();
}
})();





