版本比较
网页个性渲染通用脚本
正文
增加 2047 行删除 2 行
8 行未改动910111213141314151617181,863 行未改动全部展开1882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939308 行未改动## 一、软件简介
「网页渲染修改」是一款用户脚本(Tampermonkey 脚本),允许用户通过可视化界面修改网页中任意元素的背景样式,包括背景图片、视频、颜色、透明度、毛玻璃效果等,并支持刷新后持久化保存。
### # 使用效果(vjudge)### # 使用效果
## 二、安装与启动
### 安装要求1,863 行未改动全部展开
})();```::::## 十.1.3体验版::::info[1.3体验版]```js// ==UserScript==// @name 网页渲染修改// @namespace http://tampermonkey.net/// @version 1.3// @description 网页渲染修改 - IndexedDB 存储 + ZIP 导入导出// @author luogu fighting_man & Deepseek// @match *://*/*// @grant GM_addStyle// @grant GM_getValue// @grant GM_setValue// @grant GM_xmlhttpRequest// @grant GM_download// @grant unsafeWindow// @grant GM_info// ==/UserScript==
(function() { 'use strict';
console.log('🔍 ===== 网页渲染修改JS v1.3 已加载 =====');
const PANEL_WIDTH_RATIO = 0.25; const HIGHLIGHT_CLASS = 'bg-magician-highlight'; const SELECTED_CLASS = 'bg-magician-selected'; const STORAGE_KEY = 'bg_magician_data'; const FULLPAGE_FLAG = '__fullpage_active__';
let isPanelVisible = false; let activeElement = null; let highlightElement = null; let panelElement = null; let floatingBall = null; let domObserver = null; let lastUrl = window.location.href;
let tempParams = { bgImage: '', blur: 0, opacity: 1, color: '#ffffff', positionX: 'center', positionY: 'center', isFullPage: false, isVideo: false };
let elementDataMap = new Map(); let realtimeTimeout = null; let fullPageStyleId = 'bg-magician-fullpage-style'; let fullPageBodyStyleId = 'bg-magician-fullpage-body'; let isFullPageActive = false; let localFiles = {}; let appliedElements = new WeakSet();
// ===== IndexedDB 存储 ===== const DB_NAME = 'bg_magician_db'; const STORE_NAME = 'bg_data'; const DB_VERSION = 1;
function openDB() { return new Promise((resolve, reject) => { const request = indexedDB.open(DB_NAME, DB_VERSION); request.onupgradeneeded = function(e) { const db = e.target.result; if (!db.objectStoreNames.contains(STORE_NAME)) { db.createObjectStore(STORE_NAME, { keyPath: 'id' }); } }; request.onsuccess = function(e) { resolve(e.target.result); }; request.onerror = function(e) { reject(e.target.error); }; }); }
function saveToStorage() { openDB().then(db => { const tx = db.transaction(STORE_NAME, 'readwrite'); const store = tx.objectStore(STORE_NAME); const data = {}; data[FULLPAGE_FLAG] = isFullPageActive; for (const [selector, params] of elementDataMap) { data[selector] = params; } data['_localFiles'] = localFiles; store.put({ id: 'bg_data', data: data }); console.log('✅ 数据已保存到 IndexedDB'); }).catch(err => { console.warn('IndexedDB 保存失败:', err); }); }
function loadFromStorage() { return new Promise((resolve) => { openDB().then(db => { const tx = db.transaction(STORE_NAME, 'readonly'); const store = tx.objectStore(STORE_NAME); const request = store.get('bg_data'); request.onsuccess = function() { if (request.result) { const data = request.result.data; if (data[FULLPAGE_FLAG]) { isFullPageActive = true; delete data[FULLPAGE_FLAG]; } if (data['_localFiles']) { localFiles = data['_localFiles']; delete data['_localFiles']; } elementDataMap = new Map(Object.entries(data)); console.log('✅ 从 IndexedDB 加载了', elementDataMap.size, '条数据'); console.log('📁 加载了', Object.keys(localFiles).length, '个本地文件'); } else { console.log('ℹ️ IndexedDB 中无数据'); } resolve(); }; request.onerror = function() { console.warn('IndexedDB 读取失败'); resolve(); }; }).catch(err => { console.warn('IndexedDB 打开失败:', err); resolve(); }); }); }
// ===== JSZip 动态加载 ===== let JSZipLoaded = false; let JSZipLoading = false; let JSZipCallbacks = [];
function loadJSZip() { return new Promise((resolve, reject) => { try { if (typeof unsafeWindow.JSZip !== 'undefined') { JSZipLoaded = true; resolve(unsafeWindow.JSZip); return; } } catch (e) {}
if (JSZipLoading) { JSZipCallbacks.push({ resolve, reject }); return; }
JSZipLoading = true;
const cdnList = [ 'https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js', 'https://unpkg.com/jszip@3.10.1/dist/jszip.min.js', 'https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js' ];
let index = 0;
function tryLoad() { if (index >= cdnList.length) { JSZipLoading = false; reject('所有 CDN 加载失败'); return; }
console.log('⏳ 尝试加载 JSZip (CDN ' + (index + 1) + '):', cdnList[index]);
try { GM_xmlhttpRequest({ method: 'GET', url: cdnList[index], onload: function(response) { try { const wrapped = '(function(){' + response.responseText + '; return JSZip;})();'; const result = unsafeWindow.eval(wrapped);
if (result && typeof result === 'function') { unsafeWindow.JSZip = result; JSZipLoaded = true; JSZipLoading = false; console.log('✅ JSZip 加载成功'); resolve(result); for (const cb of JSZipCallbacks) { cb.resolve(result); } JSZipCallbacks = []; return; }
const fn = new unsafeWindow.Function(response.responseText + '\nreturn JSZip;'); const JSZip2 = fn(); if (JSZip2 && typeof JSZip2 === 'function') { unsafeWindow.JSZip = JSZip2; JSZipLoaded = true; JSZipLoading = false; console.log('✅ JSZip 加载成功'); resolve(JSZip2); for (const cb of JSZipCallbacks) { cb.resolve(JSZip2); } JSZipCallbacks = []; return; }
throw new Error('JSZip 未定义'); } catch (e) { console.warn('执行脚本失败,尝试下一个:', e); index++; tryLoad(); } }, onerror: function() { console.warn('加载失败,尝试下一个'); index++; tryLoad(); } }); } catch (e) { console.warn('GM_xmlhttpRequest 不可用,回退到 script 标签:', e); const script = document.createElement('script'); script.src = cdnList[index]; script.onload = function() { try { if (typeof unsafeWindow.JSZip !== 'undefined') { JSZipLoaded = true; JSZipLoading = false; console.log('✅ JSZip 加载成功'); resolve(unsafeWindow.JSZip); for (const cb of JSZipCallbacks) { cb.resolve(unsafeWindow.JSZip); } JSZipCallbacks = []; } else { index++; tryLoad(); } } catch (err) { index++; tryLoad(); } }; script.onerror = function() { index++; tryLoad(); }; document.head.appendChild(script); } }
tryLoad(); }); }
// ===== 工具函数 ===== function hexToRgb(hex) { const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : { r: 255, g: 255, b: 255 }; }
function rgbToRgba(hex, alpha) { const { r, g, b } = hexToRgb(hex); if (alpha === 0) return 'transparent'; if (alpha === 1) return hex; return `rgba(${r}, ${g}, ${b}, ${alpha})`; }
function getPositionValue(pos) { if (typeof pos === 'number') return pos + '%'; return pos; }
function dataURLtoBlob(dataURL) { const arr = dataURL.split(','); const mime = arr[0].match(/:(.*?);/)[1]; const bstr = atob(arr[1]); let n = bstr.length; const u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); }
function dataUrlToBlobUrl(dataUrl) { try { const blob = dataURLtoBlob(dataUrl); return URL.createObjectURL(blob); } catch (e) { console.warn('转换 Blob URL 失败:', e); return dataUrl; } }
function isVideoFile(file) { const videoTypes = ['video/mp4', 'video/webm', 'video/ogg', 'video/quicktime', 'video/x-msvideo']; return videoTypes.includes(file.type) || /\.(mp4|webm|ogg|mov|avi|mkv)$/i.test(file.name); }
function isImageFile(file) { const imageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml', 'image/webp', 'image/bmp']; return imageTypes.includes(file.type) || /\.(jpg|jpeg|png|gif|svg|webp|bmp)$/i.test(file.name); }
function fileToDataURL(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = function(e) { resolve(e.target.result); }; reader.onerror = function() { reject('读取文件失败'); }; reader.readAsDataURL(file); }); }
// ===== 选择器生成 ===== function getSelector(el) { if (!el) return null; if (el === document.body) return 'body';
if (el.id && el.id.trim() !== '') { return '#' + el.id; }
const dataAttrs = ['data-testid', 'data-id', 'data-key', 'data-name', 'data-component']; for (const attr of dataAttrs) { const val = el.getAttribute(attr); if (val) { return `[${attr}="${val}"]`; } }
if (el.className && typeof el.className === 'string') { let classes = el.className.trim().split(/\s+/) .filter(c => c !== HIGHLIGHT_CLASS && c !== SELECTED_CLASS) .filter(c => c.length > 0 && !c.startsWith('bg-magician-')) .filter(c => !/^css-/.test(c)) .filter(c => !/^[a-z0-9]{8,}$/.test(c));
if (classes.length > 0) { const tag = el.tagName.toLowerCase(); const mainClasses = classes.slice(0, 2).join('.'); return tag + '.' + mainClasses; } }
let path = []; let current = el; let maxDepth = 15;
while (current && current !== document.body && maxDepth > 0) { let tag = current.tagName.toLowerCase(); let parent = current.parentElement;
let layerSelector = tag; if (current.className && typeof current.className === 'string') { let classes = current.className.trim().split(/\s+/) .filter(c => c !== HIGHLIGHT_CLASS && c !== SELECTED_CLASS) .filter(c => c.length > 0 && !c.startsWith('bg-magician-')) .filter(c => !/^css-/.test(c)) .filter(c => !/^[a-z0-9]{8,}$/.test(c)); if (classes.length > 0) { layerSelector = tag + '.' + classes.slice(0, 2).join('.'); } }
if (parent) { const siblings = parent.querySelectorAll(tag); if (siblings.length > 1) { let index = 0; for (let i = 0; i < siblings.length; i++) { if (siblings[i] === current) { index = i + 1; break; } } layerSelector = layerSelector + ':nth-of-type(' + index + ')'; } }
path.unshift(layerSelector); current = parent; maxDepth--; }
return 'body > ' + path.join(' > '); }
function findElements(selector) { try { if (selector === 'body') return [document.body]; return document.querySelectorAll(selector); } catch (e) { return []; } }
function simplifySelector(selector) { const parts = selector.split(' > '); if (parts.length > 1) { const lastPart = parts[parts.length - 1]; if (lastPart && /^[a-z]+\.[a-zA-Z0-9_-]+/.test(lastPart)) { return lastPart; } }
const classMatch = selector.match(/\.([a-zA-Z0-9_-]+)/g); const tagMatch = selector.match(/^([a-z]+)/i); if (classMatch && classMatch.length > 0) { const tag = tagMatch ? tagMatch[1] : '*'; const classes = classMatch.map(c => c.substring(1)); const mainClasses = classes.filter(c => !/^[a-z0-9]{6,}$/.test(c)).slice(0, 2); if (mainClasses.length > 0) { return tag + '.' + mainClasses.join('.'); } }
return null; }
// ===== 动态渲染器(永不停止,跟进所有新元素) ===== function startDynamicRenderer() { console.log('🚀 启动动态渲染器');
const processedElements = new WeakSet();
function checkAndRender() { for (const [selector, params] of elementDataMap) { if (selector === 'body' && params.isFullPage) continue;
try { const elements = document.querySelectorAll(selector); for (const el of elements) { if (processedElements.has(el)) continue;
const hasBg = el.style.backgroundImage && el.style.backgroundImage !== 'none';
if (!hasBg) { render(el, params); processedElements.add(el); } else { processedElements.add(el); } } } catch (e) {} } }
checkAndRender();
const observer = new MutationObserver(() => { if (!window._renderPending) { window._renderPending = true; requestAnimationFrame(() => { window._renderPending = false; checkAndRender(); }); } });
observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['class', 'style', 'id'] });
setInterval(() => { if (!window._renderPending) { window._renderPending = true; requestAnimationFrame(() => { window._renderPending = false; checkAndRender(); }); } }, 500);
window._dynamicRenderer = { observer: observer, checkAndRender: checkAndRender, processedElements: processedElements };
console.log('✅ 动态渲染器已启动'); }
// ===== 核心:渲染 ===== function render(el, params) { if (!el) return;
appliedElements.add(el);
const selector = getSelector(el); let bgImage = params.bgImage || '';
if (bgImage === '__LOCAL_FILE__' && localFiles[selector]) { bgImage = localFiles[selector].dataUrl; }
const { blur, opacity, color, positionX, positionY, isVideo } = params; const posX = getPositionValue(positionX); const posY = getPositionValue(positionY);
let finalIsVideo = isVideo; if (localFiles[selector]) { finalIsVideo = localFiles[selector].isVideo || false; }
let bgColor; if (opacity === 0) { bgColor = 'transparent'; } else if (opacity === 1) { bgColor = color; } else { bgColor = rgbToRgba(color, opacity); }
let styleText = ''; if (bgImage && bgImage.trim() !== '') { if (finalIsVideo) { styleText += `background-image: none !important; `; } else { styleText += `background-image: url("${bgImage}") !important; `; } } else { styleText += `background-image: none !important; `; } styleText += `background-color: ${bgColor} !important; `; styleText += `background-position: ${posX} ${posY} !important; `; if (blur > 0) { styleText += `backdrop-filter: blur(${blur}px) !important; `; styleText += `-webkit-backdrop-filter: blur(${blur}px) !important; `; } else { styleText += `backdrop-filter: none !important; `; styleText += `-webkit-backdrop-filter: none !important; `; } if (!isVideo) { styleText += `background-size: cover !important; `; styleText += `background-repeat: no-repeat !important; `; }
el.style.cssText += styleText;
if (bgImage && bgImage.trim() !== '' && finalIsVideo) { createVideo(el, bgImage, { blur, opacity, color, positionX, positionY }); } else { removeVideo(el); } }
// ===== 视频背景 ===== function createVideo(el, videoUrl, params) { removeVideo(el);
let finalUrl = videoUrl; if (videoUrl && videoUrl.startsWith('data:video/')) { finalUrl = dataUrlToBlobUrl(videoUrl); }
const { blur, opacity, color, positionX, positionY } = params; let bgColor; if (opacity === 0) { bgColor = 'transparent'; } else if (opacity === 1) { bgColor = color; } else { bgColor = rgbToRgba(color, opacity); } const posX = getPositionValue(positionX); const posY = getPositionValue(positionY);
const container = document.createElement('div'); container.className = 'bg-magician-video-container'; container.style.cssText = ` position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; z-index: -1; pointer-events: none; background-color: ${bgColor}; backdrop-filter: ${blur > 0 ? `blur(${blur}px)` : 'none'}; -webkit-backdrop-filter: ${blur > 0 ? `blur(${blur}px)` : 'none'}; `;
const video = document.createElement('video'); video.src = finalUrl; video.autoplay = true; video.loop = true; video.muted = true; video.playsInline = true; video.style.cssText = ` position: absolute; top: 50%; left: 50%; min-width: 100%; min-height: 100%; width: auto; height: auto; transform: translate(-50%, -50%); object-fit: cover; `;
const posXMap = { left: '0%', center: '50%', right: '100%' }; const posYMap = { top: '0%', center: '50%', bottom: '100%' }; const finalPosX = posXMap[posX] || posX; const finalPosY = posYMap[posY] || posY; video.style.objectPosition = `${finalPosX} ${finalPosY}`;
container.appendChild(video);
if (getComputedStyle(el).position === 'static') { el.style.position = 'relative'; }
el.appendChild(container);
video.addEventListener('loadeddata', function() { video.play().catch(e => {}); });
if (video.readyState >= 2) { video.play().catch(e => {}); }
return container; }
function removeVideo(el) { const containers = el.querySelectorAll('.bg-magician-video-container'); for (const container of containers) { const video = container.querySelector('video'); if (video && video.src && video.src.startsWith('blob:')) { URL.revokeObjectURL(video.src); } container.remove(); } }
// ===== 全网页背景 ===== function applyFullPage(params) { const selector = 'body'; let bgImage = params.bgImage || '';
if (bgImage === '__LOCAL_FILE__' && localFiles[selector]) { bgImage = localFiles[selector].dataUrl; }
const { blur, opacity, color, positionX, positionY, isVideo } = params; let finalIsVideo = isVideo; if (localFiles[selector]) { finalIsVideo = localFiles[selector].isVideo || false; }
let bgColor; if (opacity === 0) { bgColor = 'transparent'; } else if (opacity === 1) { bgColor = color; } else { bgColor = rgbToRgba(color, opacity); } const posX = getPositionValue(positionX); const posY = getPositionValue(positionY);
isFullPageActive = true; saveToStorage();
const oldStyle = document.getElementById(fullPageStyleId); if (oldStyle) oldStyle.remove(); const oldBodyStyle = document.getElementById(fullPageBodyStyleId); if (oldBodyStyle) oldBodyStyle.remove();
const oldVideoContainer = document.querySelector('.bg-magician-fullpage-video'); if (oldVideoContainer) oldVideoContainer.remove();
const bodyStyleTag = document.createElement('style'); bodyStyleTag.id = fullPageBodyStyleId;
let bgImageStyle = ''; if (bgImage && bgImage.trim() !== '' && !finalIsVideo) { bgImageStyle = `background-image: url("${bgImage}") !important;`; } else { bgImageStyle = 'background-image: none !important;'; }
bodyStyleTag.textContent = ` body { ${bgImageStyle} background-color: ${bgColor} !important; background-position: ${posX} ${posY} !important; background-size: cover !important; background-repeat: no-repeat !important; background-attachment: fixed !important; min-height: 100vh !important; } `; document.head.appendChild(bodyStyleTag);
if (bgImage && bgImage.trim() !== '' && finalIsVideo) { let finalVideoUrl = bgImage; if (bgImage.startsWith('data:video/')) { finalVideoUrl = dataUrlToBlobUrl(bgImage); }
const videoContainer = document.createElement('div'); videoContainer.className = 'bg-magician-fullpage-video'; videoContainer.style.cssText = ` position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; overflow: hidden; z-index: -1; pointer-events: none; background-color: ${bgColor}; `;
const video = document.createElement('video'); video.src = finalVideoUrl; video.autoplay = true; video.loop = true; video.muted = true; video.playsInline = true; video.style.cssText = ` position: absolute; top: 50%; left: 50%; min-width: 100%; min-height: 100%; width: auto; height: auto; transform: translate(-50%, -50%); object-fit: cover; `;
const posXMap = { left: '0%', center: '50%', right: '100%' }; const posYMap = { top: '0%', center: '50%', bottom: '100%' }; const finalPosX = posXMap[posX] || posX; const finalPosY = posYMap[posY] || posY; video.style.objectPosition = `${finalPosX} ${finalPosY}`;
videoContainer.appendChild(video); document.body.appendChild(videoContainer);
video.addEventListener('loadeddata', function() { video.play().catch(e => {}); });
if (video.readyState >= 2) { video.play().catch(e => {}); } } }
function removeFullPage() { const style = document.getElementById(fullPageStyleId); if (style) style.remove(); const bodyStyle = document.getElementById(fullPageBodyStyleId); if (bodyStyle) bodyStyle.remove(); const videoContainer = document.querySelector('.bg-magician-fullpage-video'); if (videoContainer) { const video = videoContainer.querySelector('video'); if (video && video.src && video.src.startsWith('blob:')) { URL.revokeObjectURL(video.src); } videoContainer.remove(); } appliedElements.delete(document.body); isFullPageActive = false; saveToStorage(); }
// ===== 保存数据 ===== function saveData(el, params) { if (!el) return;
const selector = getSelector(el);
const saveParams = { bgImage: params.bgImage || '', blur: params.blur || 0, opacity: params.opacity !== undefined ? params.opacity : 1, color: params.color || '#ffffff', positionX: params.positionX || 'center', positionY: params.positionY || 'center', isFullPage: false, isVideo: params.isVideo || false };
if (params.bgImage && params.bgImage.startsWith('data:')) { localFiles[selector] = { dataUrl: params.bgImage, isVideo: params.isVideo || false }; saveParams.bgImage = '__LOCAL_FILE__'; }
if (selector) { elementDataMap.set(selector, saveParams); saveToStorage(); } else { console.warn('⚠️ 无法生成选择器,数据未保存'); } }
function getInfo(el) { if (!el) return null; const selector = getSelector(el); if (selector && elementDataMap.has(selector)) { const params = { ...elementDataMap.get(selector) }; if (params.bgImage === '__LOCAL_FILE__' && localFiles[selector]) { params.bgImage = localFiles[selector].dataUrl; params.isVideo = localFiles[selector].isVideo || false; } return params; } const computed = getComputedStyle(el); const bgImage = computed.backgroundImage; const bgColor = computed.backgroundColor; const bgBlur = parseFloat(computed.backdropFilter?.match(/blur\(([^)]+)\)/)?.[1]) || 0; const bgPos = computed.backgroundPosition || 'center center'; const posParts = bgPos.split(' '); let opacity = 1; let color = '#ffffff'; if (bgColor && bgColor !== 'rgba(0, 0, 0, 0)' && bgColor !== 'transparent') { const rgba = bgColor.match(/[\d.]+/g); if (rgba) { const r = Math.round(rgba[0]); const g = Math.round(rgba[1]); const b = Math.round(rgba[2]); const a = rgba[3] ? parseFloat(rgba[3]) : 1; opacity = a; color = `#${[r, g, b].map(v => v.toString(16).padStart(2, '0')).join('')}`; } } const hasVideo = el.querySelector('.bg-magician-video-container') !== null; return { bgImage: bgImage !== 'none' ? bgImage : '', blur: bgBlur, opacity: opacity, color: color, positionX: posParts[0] || 'center', positionY: posParts[1] || 'center', isFullPage: false, isVideo: hasVideo }; }
// ===== 还原元素 ===== function resetElement(el) { if (!el) return;
const selector = getSelector(el);
appliedElements.delete(el);
if (localFiles[selector]) { delete localFiles[selector]; }
if (selector === 'body' && isFullPageActive) { removeFullPage(); const stylesToRemove = [ 'background-image', 'background-color', 'backdrop-filter', '-webkit-backdrop-filter', 'background-size', 'background-position', 'background-repeat' ]; for (const style of stylesToRemove) { document.body.style.removeProperty(style); } removeVideo(document.body); elementDataMap.delete('body'); saveToStorage(); return; }
if (selector) { elementDataMap.delete(selector); saveToStorage(); }
const stylesToRemove = [ 'background-image', 'background-color', 'backdrop-filter', '-webkit-backdrop-filter', 'background-size', 'background-position', 'background-repeat' ]; for (const style of stylesToRemove) { el.style.removeProperty(style); }
removeVideo(el);
if (el.getAttribute('style') === '') { el.removeAttribute('style'); } }
// ===== 导出 ZIP ===== function exportData() { loadJSZip().then(function(JSZip) { try { const data = {}; data[FULLPAGE_FLAG] = isFullPageActive; data['_site'] = window.location.origin; data['_timestamp'] = new Date().toISOString(); data['_version'] = '1.3';
const zip = new JSZip(); let mediaCounter = 0;
for (const [selector, params] of elementDataMap) { const copy = { ...params }; if (localFiles[selector]) { const localFile = localFiles[selector]; const ext = localFile.isVideo ? 'mp4' : 'png'; const filename = 'media_' + (++mediaCounter) + '.' + ext; const blob = dataURLtoBlob(localFile.dataUrl); zip.file('media/' + filename, blob); copy.bgImage = 'media/' + filename; data[selector] = copy; } else { data[selector] = copy; } }
zip.file('data.json', JSON.stringify(data, null, 2));
zip.generateAsync({ type: 'blob' }).then(function(blob) { const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; const siteName = window.location.hostname.replace(/[^a-zA-Z0-9]/g, '_'); a.download = `bg_magic_export_${siteName}_${new Date().toISOString().slice(0,10)}.zip`; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(url), 3000);
const statusEl = document.getElementById('bg-import-status'); if (statusEl) { statusEl.textContent = '✅ 导出成功!'; statusEl.style.color = '#4a9eff'; setTimeout(() => { if (statusEl) { statusEl.textContent = '导出ZIP包,或导入ZIP备份恢复'; statusEl.style.color = '#888'; } }, 3000); } }).catch(function(err) { console.error('生成 ZIP 失败:', err); alert('生成 ZIP 失败: ' + err.message); }); } catch (e) { console.error('导出失败:', e); alert('导出失败: ' + e.message); } }).catch(function(err) { console.error('JSZip 加载失败:', err); alert('JSZip 加载失败,请检查网络后重试'); }); }
// ===== 导入 ZIP ===== function importZip(file) { return new Promise((resolve, reject) => { loadJSZip().then(function(JSZip) { const reader = new FileReader(); reader.onload = async function(e) { try { const zipData = e.target.result; const zip = await JSZip.loadAsync(zipData);
const jsonFile = zip.file('data.json'); if (!jsonFile) { reject('ZIP 中缺少 data.json 文件'); return; }
const jsonContent = await jsonFile.async('string'); const data = JSON.parse(jsonContent);
if (typeof data !== 'object') { reject('数据格式无效'); return; }
let hasValidData = false; const newMap = new Map(); const newLocalFiles = {};
for (const [key, value] of Object.entries(data)) { if (key === '_site' || key === '_timestamp' || key === '_version' || key === FULLPAGE_FLAG) { continue; } if (typeof value === 'object' && value !== null) { newMap.set(key, value); hasValidData = true; } }
if (!hasValidData) { reject('没有找到有效的背景数据'); return; }
for (const [selector, params] of newMap) { const bgImage = params.bgImage || ''; if (bgImage.startsWith('media/')) { const filename = bgImage.replace('media/', ''); const mediaFile = zip.file('media/' + filename); if (mediaFile) { const blob = await mediaFile.async('blob'); const dataUrl = await new Promise((resolve2) => { const reader2 = new FileReader(); reader2.onload = function(e) { resolve2(e.target.result); }; reader2.readAsDataURL(blob); }); params.bgImage = '__LOCAL_FILE__'; newLocalFiles[selector] = { dataUrl: dataUrl, isVideo: dataUrl.startsWith('data:video/') }; } else { params.bgImage = ''; } } }
Object.assign(localFiles, newLocalFiles);
if (elementDataMap.size > 0) { if (!confirm(`当前网站有 ${elementDataMap.size} 条数据,是否覆盖?\n\n选择"确定"覆盖,选择"取消"追加数据。`)) { for (const [key, value] of newMap) { if (!elementDataMap.has(key)) { elementDataMap.set(key, value); } } } else { elementDataMap = newMap; } } else { elementDataMap = newMap; }
if (data[FULLPAGE_FLAG] !== undefined) { isFullPageActive = data[FULLPAGE_FLAG]; }
saveToStorage(); resolve(elementDataMap.size); } catch (err) { reject('导入失败: ' + err.message); } }; reader.onerror = function() { reject('读取文件失败'); }; reader.readAsArrayBuffer(file); }).catch(function(err) { reject('JSZip 加载失败: ' + err); }); }); }
// ===== 高亮/选择 ===== function clearHighlights() { document.querySelectorAll(`.${HIGHLIGHT_CLASS}`).forEach(el => el.classList.remove(HIGHLIGHT_CLASS)); highlightElement = null; }
function clearSelected() { if (activeElement) { activeElement.classList.remove(SELECTED_CLASS); activeElement = null; } }
function addHighlight(el) { clearHighlights(); if (el) { el.classList.add(HIGHLIGHT_CLASS); highlightElement = el; } }
function toggleSelected(el) { if (activeElement === el) { clearSelected(); updatePanelContent(null); return; } clearSelected(); if (el) { el.classList.add(SELECTED_CLASS); activeElement = el; const info = getInfo(el); if (info) { tempParams = { ...info }; } updatePanelContent(el); render(el, tempParams); } else { updatePanelContent(null); } }
// ===== 鼠标事件 ===== function onMouseOver(e) { if (!isPanelVisible) return; const target = e.target; if (panelElement && panelElement.contains(target)) return; if (floatingBall && floatingBall.contains(target)) return; addHighlight(target); }
function onMouseOut(e) { if (!isPanelVisible) return; const target = e.target; if (panelElement && panelElement.contains(target)) return; if (floatingBall && floatingBall.contains(target)) return; if (highlightElement === target) { clearHighlights(); } }
function onClick(e) { if (!isPanelVisible) return; const target = e.target; if (panelElement && panelElement.contains(target)) return; if (floatingBall && floatingBall.contains(target)) return; if (highlightElement === target) { toggleSelected(target); e.preventDefault(); e.stopPropagation(); } else { clearSelected(); clearHighlights(); updatePanelContent(null); } }
// ===== SPA路由变化检测 ===== function checkUrlChange() { const currentUrl = window.location.href; if (currentUrl !== lastUrl) { lastUrl = currentUrl;
if (window._dynamicRenderer) { window._dynamicRenderer.processedElements = new WeakSet(); setTimeout(() => { window._dynamicRenderer.checkAndRender(); }, 200); } } }
// ===== UI ===== function createFloatingBall() { if (floatingBall) return; floatingBall = document.createElement('div'); floatingBall.id = 'bg-magician-ball'; floatingBall.textContent = '🎨'; floatingBall.title = '打开网页渲染修改'; document.body.appendChild(floatingBall); floatingBall.addEventListener('click', function(e) { e.stopPropagation(); showPanel(); }); }
function createPanel() { if (panelElement) return;
GM_addStyle(` .${HIGHLIGHT_CLASS} { outline: 3px solid rgba(173, 216, 230, 0.7) !important; outline-offset: -3px !important; } .${SELECTED_CLASS} { outline: 3px solid rgba(218, 112, 214, 0.8) !important; outline-offset: -3px !important; } #bg-magician-ball { position: fixed; bottom: 30px; right: 30px; width: 50px; height: 50px; background: #4a4a6a; color: white; font-size: 24px; display: flex; align-items: center; justify-content: center; cursor: pointer; z-index: 2147483647; user-select: none; border: 1px solid #666; border-radius: 50%; box-shadow: 0 2px 12px rgba(0,0,0,0.3); } #bg-magician-ball:hover { background: #5a5a7a; transform: scale(1.05); } #bg-magician-panel { position: fixed; top: 0; right: 0; width: ${PANEL_WIDTH_RATIO * 100}%; height: 100%; background: #2a2a2a; color: #ddd; font-family: Arial, sans-serif; font-size: 13px; z-index: 2147483646; display: flex; flex-direction: column; padding: 15px 20px; box-sizing: border-box; overflow-y: auto; border-left: 1px solid #444; transition: transform 0.3s ease; transform: translateX(100%); pointer-events: none; } #bg-magician-panel.visible { transform: translateX(0); pointer-events: auto; } #bg-magician-panel .panel-header { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #444; padding-bottom: 8px; margin-bottom: 15px; } #bg-magician-panel .panel-header h2 { margin: 0; color: #ccc; font-size: 18px; font-weight: normal; } #bg-magician-panel .panel-close { background: none; border: none; color: #888; font-size: 22px; cursor: pointer; padding: 0 4px; line-height: 1; } #bg-magician-panel .panel-close:hover { color: #ff6b6b; } #bg-magician-panel .param-group { margin-bottom: 12px; } #bg-magician-panel label { display: block; margin-bottom: 3px; font-size: 12px; color: #aaa; } #bg-magician-panel input[type="text"], #bg-magician-panel input[type="color"] { width: 100%; padding: 6px 8px; background: #3a3a3a; border: 1px solid #555; color: #ddd; box-sizing: border-box; font-size: 13px; border-radius: 4px; } #bg-magician-panel input[type="range"] { width: 100%; margin: 4px 0; background: transparent; accent-color: #666; } #bg-magician-panel .range-labels { display: flex; justify-content: space-between; font-size: 11px; color: #777; } #bg-magician-panel .range-value { float: right; color: #888; font-size: 12px; } #bg-magician-panel .button-group { display: flex; gap: 8px; margin-top: 15px; flex-wrap: wrap; } #bg-magician-panel .button-group button { flex: 1; padding: 8px 16px; font-size: 14px; cursor: pointer; border: 1px solid #666; color: white; min-width: 60px; border-radius: 4px; } #bg-magician-panel .save-btn { background: #4a4a6a; } #bg-magician-panel .save-btn:hover { background: #5a5a7a; } #bg-magician-panel .reset-btn { background: #6a3a3a; } #bg-magician-panel .reset-btn:hover { background: #7a4a4a; } #bg-magician-panel .remove-fullpage-btn { background: #5a3a2a; } #bg-magician-panel .remove-fullpage-btn:hover { background: #6a4a3a; } #bg-magician-panel .position-group { display: flex; gap: 8px; align-items: center; } #bg-magician-panel .position-group select { flex: 1; padding: 6px 8px; background: #3a3a3a; border: 1px solid #555; color: #ddd; font-size: 13px; border-radius: 4px; } #bg-magician-panel .hint-text { text-align: center; margin-top: 8px; font-size: 11px; color: #555; } #bg-magician-panel .status-text { text-align: center; margin-top: 5px; font-size: 11px; color: #888; border-top: 1px solid #333; padding-top: 8px; } #bg-magician-panel .fp-section { border-top: 1px solid #444; padding-top: 12px; margin-top: 5px; } #bg-magician-panel .fp-section .fp-label { font-size: 12px; color: #aaa; margin-bottom: 6px; display: block; } #bg-magician-panel .fp-section .fp-row { display: flex; gap: 8px; } #bg-magician-panel .fp-section .fp-row input[type="text"] { flex: 1; padding: 6px 8px; background: #3a3a3a; border: 1px solid #555; color: #ddd; box-sizing: border-box; font-size: 13px; border-radius: 4px; } #bg-magician-panel .fp-section .fp-row button { padding: 6px 16px; background: #2a5a4a; color: white; border: 1px solid #666; font-size: 13px; cursor: pointer; white-space: nowrap; border-radius: 4px; } #bg-magician-panel .fp-section .fp-row button:hover { background: #3a6a5a; } #bg-magician-panel .fp-section .fp-status { margin-top: 6px; font-size: 11px; color: #888; }
#bg-magician-panel .file-upload-area { border: 2px dashed #555; padding: 12px; margin-top: 6px; text-align: center; cursor: pointer; transition: border-color 0.3s; border-radius: 4px; } #bg-magician-panel .file-upload-area:hover { border-color: #888; } #bg-magician-panel .file-upload-area input[type="file"] { display: none; } #bg-magician-panel .file-upload-area .file-label { color: #888; font-size: 12px; cursor: pointer; } #bg-magician-panel .file-upload-area .file-label:hover { color: #aaa; } #bg-magician-panel .file-upload-area .file-name { color: #4a9eff; font-size: 11px; margin-top: 4px; word-break: break-all; }
.bg-magician-video-container { position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; z-index: -1; pointer-events: none; } .bg-magician-video-container video { position: absolute; top: 50%; left: 50%; min-width: 100%; min-height: 100%; width: auto; height: auto; transform: translate(-50%, -50%); object-fit: cover; } .bg-magician-fullpage-video { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; overflow: hidden; z-index: -1; pointer-events: none; } .bg-magician-fullpage-video video { position: absolute; top: 50%; left: 50%; min-width: 100%; min-height: 100%; width: auto; height: auto; transform: translate(-50%, -50%); object-fit: cover; } `);
panelElement = document.createElement('div'); panelElement.id = 'bg-magician-panel'; panelElement.innerHTML = ` <div class="panel-header"> <h2>网页渲染修改 <span style="font-size:11px;color:#666;">v1.3</span></h2> <button class="panel-close" id="bg-panel-close">✕</button> </div> <div id="bg-panel-content"> <div class="param-group"> <label>背景媒体 URL</label> <input type="text" id="bg-image-input" placeholder="输入图片URL 或 视频URL" /> <div style="font-size:10px;color:#666;margin-top:3px;"> 支持: 图片 (jpg/png/gif/svg/webp) 或 视频 (mp4/webm/ogg/mov) </div> </div>
<div class="param-group"> <label>或选择本地文件</label> <div class="file-upload-area" id="local-file-area"> <span class="file-label">📁 点击选择本地图片或视频</span> <input type="file" id="local-file-input" accept="image/*,video/*" /> <div class="file-name" id="local-file-name"></div> </div> </div>
<div class="param-group"> <label>媒体位置</label> <div class="position-group"> <select id="bg-position-x"> <option value="left">左</option> <option value="center" selected>中</option> <option value="right">右</option> <option value="0%">0%</option> <option value="25%">25%</option> <option value="50%">50%</option> <option value="75%">75%</option> <option value="100%">100%</option> </select> <select id="bg-position-y"> <option value="top">上</option> <option value="center" selected>中</option> <option value="bottom">下</option> <option value="0%">0%</option> <option value="25%">25%</option> <option value="50%">50%</option> <option value="75%">75%</option> <option value="100%">100%</option> </select> </div> </div> <div class="param-group"> <label>毛玻璃模糊</label> <input type="range" id="bg-blur-range" min="0" max="30" step="0.5" value="0" /> <div class="range-labels"><span>0</span><span>30</span></div> <span class="range-value" id="bg-blur-value">0 px</span> </div> <div class="param-group"> <label>背景透明度</label> <input type="range" id="bg-opacity-range" min="0" max="1" step="0.05" value="1" /> <div class="range-labels"><span>0 (透明)</span><span>1 (不透明)</span></div> <span class="range-value" id="bg-opacity-value">1.00</span> </div> <div class="param-group"> <label>背景颜色</label> <input type="color" id="bg-color-input" value="#ffffff" /> </div> <div class="button-group"> <button class="save-btn" id="bg-save-btn">💾 保存当前元素</button> <button class="remove-fullpage-btn" id="bg-remove-fullpage-btn">🚫 取消全网页</button> <button class="reset-btn" id="bg-reset-btn">↩️ 还原当前元素</button> </div>
<div class="fp-section"> <span class="fp-label">🌐 全网页背景</span> <div class="fp-row"> <input type="text" id="fp-url-input" placeholder="输入图片或视频URL" /> <button id="fp-apply-btn">应用</button> </div> <div class="file-upload-area" id="fp-local-file-area" style="margin-top:6px;padding:10px;"> <span class="file-label">📁 选择本地文件作为全网页背景</span> <input type="file" id="fp-local-file-input" accept="image/*,video/*" /> <div class="file-name" id="fp-local-file-name"></div> </div> <div class="fp-status" id="fp-status-text">输入媒体URL或选择本地文件,点击应用为全网页背景</div> </div>
<div class="fp-section"> <span class="fp-label" style="color:#4a9eff;">📦 数据管理</span> <div class="fp-row"> <button id="bg-export-btn" style="flex:1;background:#3a5a4a;color:white;border:1px solid #666;padding:6px 12px;cursor:pointer;font-size:13px;border-radius:4px;">⬇️ 导出ZIP</button> <button id="bg-import-btn" style="flex:1;background:#3a4a6a;color:white;border:1px solid #666;padding:6px 12px;cursor:pointer;font-size:13px;border-radius:4px;">⬆️ 导入ZIP</button> </div> <input type="file" id="bg-import-file" accept=".zip" style="display:none;" /> <div class="fp-status" id="bg-import-status" style="margin-top:4px;font-size:11px;color:#888;">导出ZIP包,或导入ZIP备份恢复</div> </div>
<div class="status-text" id="bg-status-text">💡 新元素出现时自动渲染</div> </div> `; document.body.appendChild(panelElement);
// ===== 本地文件选择 ===== const localFileInput = document.getElementById('local-file-input'); const localFileName = document.getElementById('local-file-name'); const localFileArea = document.getElementById('local-file-area');
localFileArea.addEventListener('click', function(e) { if (e.target.tagName !== 'INPUT') { localFileInput.click(); } });
localFileInput.addEventListener('change', async function(e) { const file = e.target.files[0]; if (!file) return; try { const dataUrl = await fileToDataURL(file); const isVideo = isVideoFile(file); document.getElementById('bg-image-input').value = dataUrl; localFileName.textContent = '📎 ' + file.name + ' (' + (file.size / 1024 / 1024).toFixed(2) + ' MB)'; tempParams.bgImage = dataUrl; tempParams.isVideo = isVideo; if (activeElement) { const stylesToRemove = [ 'background-image', 'background-color', 'backdrop-filter', '-webkit-backdrop-filter', 'background-size', 'background-position', 'background-repeat' ]; for (const style of stylesToRemove) { activeElement.style.removeProperty(style); } removeVideo(activeElement); render(activeElement, tempParams); } document.getElementById('bg-status-text').textContent = '✅ 本地文件已加载: ' + file.name; setTimeout(() => { document.getElementById('bg-status-text').textContent = '💡 新元素出现时自动渲染'; }, 2000); } catch (err) { alert('加载文件失败: ' + err); } e.target.value = ''; });
// ===== 全网页本地文件 ===== const fpLocalFileInput = document.getElementById('fp-local-file-input'); const fpLocalFileName = document.getElementById('fp-local-file-name'); const fpLocalFileArea = document.getElementById('fp-local-file-area');
fpLocalFileArea.addEventListener('click', function(e) { if (e.target.tagName !== 'INPUT') { fpLocalFileInput.click(); } });
fpLocalFileInput.addEventListener('change', async function(e) { const file = e.target.files[0]; if (!file) return; try { const dataUrl = await fileToDataURL(file); const isVideo = isVideoFile(file); document.getElementById('fp-url-input').value = dataUrl; fpLocalFileName.textContent = '📎 ' + file.name + ' (' + (file.size / 1024 / 1024).toFixed(2) + ' MB)';
const selector = 'body'; localFiles[selector] = { dataUrl: dataUrl, isVideo: isVideo };
const fpParams = { bgImage: '__LOCAL_FILE__', blur: 0, opacity: 1, color: '#ffffff', positionX: 'center', positionY: 'center', isFullPage: true, isVideo: isVideo }; elementDataMap.set('body', { ...fpParams, isFullPage: true }); saveToStorage(); removeFullPage(); applyFullPage(fpParams); document.getElementById('fp-status-text').textContent = '✅ 全网页背景已应用(本地文件)'; setTimeout(() => { document.getElementById('fp-status-text').textContent = '输入媒体URL或选择本地文件,点击应用为全网页背景'; }, 3000); } catch (err) { alert('加载文件失败: ' + err); } e.target.value = ''; });
// ===== 导入导出 ===== document.getElementById('bg-export-btn').addEventListener('click', function() { exportData(); });
document.getElementById('bg-import-btn').addEventListener('click', function() { document.getElementById('bg-import-file').click(); });
document.getElementById('bg-import-file').addEventListener('change', async function(e) { const file = e.target.files[0]; if (!file) return;
try { const count = await importZip(file); document.getElementById('bg-import-status').textContent = `✅ 成功导入 ${count} 条数据,刷新页面生效`; document.getElementById('bg-import-status').style.color = '#4a9eff'; if (window._dynamicRenderer) { window._dynamicRenderer.processedElements = new WeakSet(); window._dynamicRenderer.checkAndRender(); } setTimeout(() => { document.getElementById('bg-import-status').textContent = '导出ZIP包,或导入ZIP备份恢复'; document.getElementById('bg-import-status').style.color = '#888'; }, 5000); } catch (err) { document.getElementById('bg-import-status').textContent = '❌ 导入失败: ' + err; document.getElementById('bg-import-status').style.color = '#ff6b6b'; setTimeout(() => { document.getElementById('bg-import-status').textContent = '导出ZIP包,或导入ZIP备份恢复'; document.getElementById('bg-import-status').style.color = '#888'; }, 5000); console.error('导入失败:', err); } e.target.value = ''; });
// ===== 事件绑定 ===== function onParamChange() { const url = document.getElementById('bg-image-input').value.trim(); tempParams.bgImage = url; tempParams.isVideo = url.includes('.mp4') || url.includes('.webm') || url.includes('.ogg') || url.includes('.mov'); tempParams.blur = parseFloat(document.getElementById('bg-blur-range').value); tempParams.opacity = parseFloat(document.getElementById('bg-opacity-range').value); tempParams.color = document.getElementById('bg-color-input').value; tempParams.positionX = document.getElementById('bg-position-x').value; tempParams.positionY = document.getElementById('bg-position-y').value;
if (activeElement) { const stylesToRemove = [ 'background-image', 'background-color', 'backdrop-filter', '-webkit-backdrop-filter', 'background-size', 'background-position', 'background-repeat' ]; for (const style of stylesToRemove) { activeElement.style.removeProperty(style); } removeVideo(activeElement); render(activeElement, tempParams); } }
function debouncedRender() { if (realtimeTimeout) clearTimeout(realtimeTimeout); realtimeTimeout = setTimeout(onParamChange, 50); }
document.getElementById('bg-image-input').addEventListener('input', debouncedRender); document.getElementById('bg-blur-range').addEventListener('input', debouncedRender); document.getElementById('bg-opacity-range').addEventListener('input', debouncedRender); document.getElementById('bg-color-input').addEventListener('input', debouncedRender); document.getElementById('bg-position-x').addEventListener('change', debouncedRender); document.getElementById('bg-position-y').addEventListener('change', debouncedRender);
// ===== 保存按钮 ===== document.getElementById('bg-save-btn').addEventListener('click', function() { if (activeElement) { const url = document.getElementById('bg-image-input').value.trim(); tempParams.bgImage = url; tempParams.isVideo = url.includes('.mp4') || url.includes('.webm') || url.includes('.ogg') || url.includes('.mov'); saveData(activeElement, tempParams); render(activeElement, tempParams); document.getElementById('bg-status-text').textContent = '✅ 已保存到 IndexedDB!'; setTimeout(() => { document.getElementById('bg-status-text').textContent = '💡 新元素出现时自动渲染'; }, 2000); } else { alert('请先点击选择一个背景元素'); } });
// ===== 全网页应用 ===== document.getElementById('fp-apply-btn').addEventListener('click', function() { const url = document.getElementById('fp-url-input').value.trim(); if (!url) { document.getElementById('fp-status-text').textContent = '⚠️ 请输入媒体URL或选择本地文件'; return; } const isVideo = url.includes('.mp4') || url.includes('.webm') || url.includes('.ogg') || url.includes('.mov'); const fpParams = { bgImage: url, blur: 0, opacity: 1, color: '#ffffff', positionX: 'center', positionY: 'center', isFullPage: true, isVideo: isVideo }; elementDataMap.set('body', { ...fpParams, isFullPage: true }); saveToStorage(); removeFullPage(); applyFullPage(fpParams); document.getElementById('fp-status-text').textContent = '✅ 全网页背景已应用!'; setTimeout(() => { document.getElementById('fp-status-text').textContent = '输入媒体URL或选择本地文件,点击应用为全网页背景'; }, 2000); });
// ===== 取消全网页 ===== document.getElementById('bg-remove-fullpage-btn').addEventListener('click', function() { if (isFullPageActive) { if (confirm('确定要取消全网页背景吗?')) { removeFullPage(); elementDataMap.delete('body'); saveToStorage(); const stylesToRemove = [ 'background-image', 'background-color', 'backdrop-filter', '-webkit-backdrop-filter', 'background-size', 'background-position', 'background-repeat' ]; for (const style of stylesToRemove) { document.body.style.removeProperty(style); } document.getElementById('bg-status-text').textContent = '🚫 已取消全网页背景'; clearSelected(); clearHighlights(); setTimeout(() => { document.getElementById('bg-status-text').textContent = '💡 新元素出现时自动渲染'; }, 2000); } } else { alert('当前没有全网页背景'); } });
// ===== 还原按钮 ===== document.getElementById('bg-reset-btn').addEventListener('click', function() { if (activeElement) { if (confirm('确定要还原该元素到原始状态吗?')) { resetElement(activeElement); tempParams = { bgImage: '', blur: 0, opacity: 1, color: '#ffffff', positionX: 'center', positionY: 'center', isFullPage: false, isVideo: false }; updatePanelContent(activeElement); document.getElementById('bg-status-text').textContent = '↩️ 已还原当前元素'; clearSelected(); clearHighlights(); } } else { alert('请先点击选择一个背景元素'); } });
document.getElementById('bg-panel-close').addEventListener('click', function() { hidePanel(); });
document.getElementById('fp-url-input').addEventListener('keydown', function(e) { if (e.key === 'Enter') { document.getElementById('fp-apply-btn').click(); } });
panelElement.classList.remove('visible'); }
function updatePanelContent(el) { if (!document.getElementById('bg-panel-content')) return; const imageInput = document.getElementById('bg-image-input'); const blurRange = document.getElementById('bg-blur-range'); const blurValue = document.getElementById('bg-blur-value'); const opacityRange = document.getElementById('bg-opacity-range'); const opacityValue = document.getElementById('bg-opacity-value'); const colorInput = document.getElementById('bg-color-input'); const posXSelect = document.getElementById('bg-position-x'); const posYSelect = document.getElementById('bg-position-y');
if (!el) { imageInput.value = ''; blurRange.value = 0; blurValue.textContent = '0 px'; opacityRange.value = 1; opacityValue.textContent = '1.00'; colorInput.value = '#ffffff'; posXSelect.value = 'center'; posYSelect.value = 'center'; tempParams = { bgImage: '', blur: 0, opacity: 1, color: '#ffffff', positionX: 'center', positionY: 'center', isFullPage: false, isVideo: false }; return; }
const info = getInfo(el); if (!info) { imageInput.value = ''; blurRange.value = 0; blurValue.textContent = '0 px'; opacityRange.value = 1; opacityValue.textContent = '1.00'; colorInput.value = '#ffffff'; posXSelect.value = 'center'; posYSelect.value = 'center'; tempParams = { bgImage: '', blur: 0, opacity: 1, color: '#ffffff', positionX: 'center', positionY: 'center', isFullPage: false, isVideo: false }; return; }
imageInput.value = info.bgImage || ''; blurRange.value = info.blur || 0; blurValue.textContent = (info.blur || 0) + ' px'; opacityRange.value = info.opacity || 1; opacityValue.textContent = (info.opacity || 1).toFixed(2); let color = info.color || '#ffffff'; if (color.startsWith('rgba')) { const parts = color.match(/[\d.]+/g); if (parts && parts.length >= 3) { color = `#${[parts[0], parts[1], parts[2]].map(v => Math.round(parseFloat(v)).toString(16).padStart(2, '0')).join('')}`; } else { color = '#ffffff'; } } colorInput.value = color; posXSelect.value = info.positionX || 'center'; posYSelect.value = info.positionY || 'center'; tempParams = { ...info }; }
function showPanel() { if (!panelElement) createPanel(); if (!floatingBall) createFloatingBall();
isPanelVisible = true; panelElement.classList.add('visible'); floatingBall.style.display = 'none';
document.addEventListener('mouseover', onMouseOver); document.addEventListener('mouseout', onMouseOut); document.addEventListener('click', onClick, true);
if (activeElement) { updatePanelContent(activeElement); } else { updatePanelContent(null); } document.body.style.marginRight = `${PANEL_WIDTH_RATIO * 100}%`; }
function hidePanel() { if (!panelElement) return;
isPanelVisible = false; panelElement.classList.remove('visible'); if (floatingBall) { floatingBall.style.display = 'flex'; }
document.removeEventListener('mouseover', onMouseOver); document.removeEventListener('mouseout', onMouseOut); document.removeEventListener('click', onClick, true);
clearHighlights(); clearSelected(); document.body.style.marginRight = '0'; }
function cleanupOldData() { let cleaned = 0; for (const [selector] of elementDataMap) { if (selector.includes(HIGHLIGHT_CLASS) || selector.includes(SELECTED_CLASS)) { elementDataMap.delete(selector); cleaned++; } } if (elementDataMap.has(FULLPAGE_FLAG)) { elementDataMap.delete(FULLPAGE_FLAG); cleaned++; } if (cleaned > 0) { console.log('🧹 清理了', cleaned, '条旧数据'); saveToStorage(); } }
// ===== 初始化 ===== if (document.readyState === 'complete') { init(); } else { window.addEventListener('load', init); }
async function init() { await loadFromStorage(); cleanupOldData(); createPanel(); createFloatingBall();
if (panelElement) { panelElement.classList.remove('visible'); isPanelVisible = false; } if (floatingBall) { floatingBall.style.display = 'flex'; } document.body.style.marginRight = '0';
loadJSZip().then(function() { console.log('✅ JSZip 已预加载'); }).catch(function(e) { console.warn('⚠️ JSZip 预加载失败:', e); });
if (isFullPageActive && elementDataMap.has('body')) { const bodyParams = elementDataMap.get('body'); if (bodyParams && bodyParams.isFullPage) { console.log('🌐 立即应用全网页背景'); applyFullPage(bodyParams); } }
// 再启动动态渲染器(处理其他元素) startDynamicRenderer();
setInterval(checkUrlChange, 500);
console.log('✅ 网页渲染修改JS v1.3 初始化完成'); }
document.addEventListener('keydown', function(e) { if (e.ctrlKey && e.altKey && e.key === 'p') { e.preventDefault(); if (isPanelVisible) hidePanel(); else showPanel(); } if (e.key === 'Escape' && isPanelVisible) { hidePanel(); } });
// ===== 暴露全局接口 ===== window.bgMagician = { showPanel: showPanel, hidePanel: hidePanel, data: elementDataMap, resetElement: resetElement, removeFullPage: removeFullPage, isFullPageActive: () => isFullPageActive, exportData: exportData, importZip: importZip, render: render, saveToStorage: saveToStorage, getSelector: getSelector, findElements: findElements, clearAll: function() { elementDataMap.clear(); localFiles = {}; removeFullPage(); saveToStorage(); console.log('🗑️ 已清除所有数据'); } };
})();```::::