JavaScript// ==UserScript==
// @name 网页渲染修改
// @namespace http://tampermonkey.net/
// @version 1.0
// @description 网页渲染修改 - DOM树位置模式
// @author luogu fighting_man & Deepseek
// @match *://*/*
// @grant GM_addStyle
// ==/UserScript==
(function() {
'use strict';
console.log('🔍 ===== 网页渲染修改JS v1.0 已加载 =====');
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__';
const MAX_RETRIES = 10;
const RETRY_INTERVAL = 500;
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;
// ===== 工具函数 =====
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 saveToStorage() {
try {
const data = {};
data[FULLPAGE_FLAG] = isFullPageActive;
for (const [selector, params] of elementDataMap) {
data[selector] = params;
}
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
console.log('✅ 数据已保存');
} catch (e) {
console.warn('保存失败:', e);
}
}
function loadFromStorage() {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return;
const data = JSON.parse(raw);
if (data[FULLPAGE_FLAG]) {
isFullPageActive = true;
delete data[FULLPAGE_FLAG];
}
elementDataMap = new Map(Object.entries(data));
console.log('✅ 加载了', elementDataMap.size, '条数据');
} catch (e) {
console.warn('加载失败:', e);
}
}
// ===== DOM树位置选择器生成 =====
function getElementSelector(el) {
if (!el) return null;
if (el === document.body) return 'body';
// 1. 有ID直接用ID
if (el.id && el.id.trim() !== '') {
return '#' + el.id;
}
// 2. 使用data-*属性
const dataAttrs = ['data-testid', 'data-id', 'data-key', 'data-name'];
for (const attr of dataAttrs) {
const val = el.getAttribute(attr);
if (val) {
return `[${attr}="${val}"]`;
}
}
// 3. 使用稳定的class组合(过滤动态哈希)
let classSelector = '';
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) {
classSelector = el.tagName.toLowerCase() + '.' + classes.join('.');
}
}
// 4. 生成完整路径(从body到元素的路径)
let path = [];
let current = el;
let maxDepth = 15;
while (current && current !== document.body && maxDepth > 0) {
let tag = current.tagName.toLowerCase();
let parent = current.parentElement;
// 尝试用class定位当前层
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.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--;
}
// 如果路径只有一个元素且是class选择器,直接返回
if (path.length === 1 && classSelector) {
return classSelector;
}
// 返回完整路径
return 'body > ' + path.join(' > ');
}
// ===== 查找元素 =====
function findElementBySelector(selector) {
try {
if (selector === 'body') return document.body;
// 直接查询
let el = document.querySelector(selector);
if (el) return el;
// 如果选择器包含 > ,逐级查找
if (selector.includes(' > ')) {
const parts = selector.split(' > ');
let current = document.body;
let matched = true;
for (let part of parts) {
if (part === 'body') continue;
let found = current.querySelector(part);
if (found) {
current = found;
} else {
// 尝试用标签名匹配
let tag = part.split(':')[0].split('.')[0];
let children = current.children;
let foundChild = null;
for (let child of children) {
if (child.tagName.toLowerCase() === tag) {
foundChild = child;
break;
}
}
if (foundChild) {
current = foundChild;
} else {
matched = false;
break;
}
}
}
if (matched && current !== document.body) {
return current;
}
}
// 兜底
const all = document.querySelectorAll(selector);
if (all.length > 0) return all[0];
return null;
} catch (e) {
return null;
}
}
function findAllElementsBySelector(selector) {
try {
if (selector === 'body') return [document.body];
return document.querySelectorAll(selector);
} catch (e) {
return [];
}
}
// ===== 等待元素出现 =====
function restoreElementWithRetry(selector, params, retries = MAX_RETRIES) {
if (retries <= 0) {
console.warn('⚠️ 重试次数用尽,放弃恢复元素:', selector);
return;
}
const elements = findAllElementsBySelector(selector);
if (elements.length > 0) {
for (const el of elements) {
console.log('✅ 找到元素,应用背景:', selector);
realtimeRender(el, params);
}
return;
}
console.log(`⏳ 等待元素出现 (${retries}次重试): ${selector}`);
setTimeout(() => {
restoreElementWithRetry(selector, params, retries - 1);
}, RETRY_INTERVAL);
}
// ===== 核心:临时渲染 =====
function realtimeRender(el, params) {
if (!el) return;
const { bgImage, blur, opacity, color, positionX, positionY, isVideo } = params;
const posX = getPositionValue(positionX);
const posY = getPositionValue(positionY);
// 处理背景色
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 (isVideo) {
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() !== '' && isVideo) {
createVideoBackground(el, bgImage, params);
} else {
removeVideoBackground(el);
}
}
// ===== 视频背景 =====
function createVideoBackground(el, videoUrl, params) {
removeVideoBackground(el);
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 = videoUrl;
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.play().catch(e => console.log('视频自动播放失败:', e));
return container;
}
function removeVideoBackground(el) {
const containers = el.querySelectorAll('.bg-magician-video-container');
for (const container of containers) {
container.remove();
}
}
// ===== 全网页背景 =====
function applyFullPageBackground(params) {
const { bgImage, blur, opacity, color, positionX, positionY, isVideo } = 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);
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() !== '' && !isVideo) {
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() !== '' && isVideo) {
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 = bgImage;
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.play().catch(e => console.log('视频自动播放失败:', e));
console.log('✅ 全网页视频背景已创建');
}
console.log('✅ 全网页背景已应用');
}
function removeFullPageBackground() {
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) videoContainer.remove();
isFullPageActive = false;
saveToStorage();
console.log('✅ 已移除全网页背景样式');
}
// ===== 保存数据(只存数据,不修改DOM) =====
function saveData(el, params) {
if (!el) return;
const selector = getElementSelector(el);
console.log('💾 保存数据,选择器:', selector);
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 (selector) {
// 检查是否已有相同选择器的数据,如果有则覆盖
elementDataMap.set(selector, saveParams);
saveToStorage();
console.log('✅ 数据已保存到 localStorage');
} else {
console.warn('⚠️ 无法生成选择器,数据未保存');
}
}
function getBackgroundInfo(el) {
if (!el) return null;
const selector = getElementSelector(el);
if (selector && elementDataMap.has(selector)) {
return { ...elementDataMap.get(selector) };
}
// 从元素计算样式读取
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 applyStoredData() {
console.log('🔄 应用存储的数据(DOM树位置模式)...');
if (isFullPageActive && elementDataMap.has('body')) {
const bodyParams = elementDataMap.get('body');
if (bodyParams && bodyParams.isFullPage) {
applyFullPageBackground(bodyParams);
}
}
let applied = 0;
for (const [selector, params] of elementDataMap) {
if (selector === 'body' && params.isFullPage) continue;
const elements = findAllElementsBySelector(selector);
if (elements.length > 0) {
for (const el of elements) {
realtimeRender(el, params);
applied++;
}
} else {
console.log(`⏳ 元素暂未出现: ${selector}`);
restoreElementWithRetry(selector, params);
}
}
if (applied > 0) {
console.log(`✅ 已应用 ${applied} 个元素的背景`);
}
}
function resetElement(el) {
if (!el) return;
const selector = getElementSelector(el);
console.log('🔄 还原元素:', selector || el.tagName);
if (selector === 'body' && isFullPageActive) {
removeFullPageBackground();
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);
}
removeVideoBackground(document.body);
elementDataMap.delete('body');
saveToStorage();
console.log('✅ 已还原全网页背景');
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);
}
removeVideoBackground(el);
if (el.getAttribute('style') === '') {
el.removeAttribute('style');
}
console.log('✅ 已还原单元素背景');
}
// ===== 高亮/选择 =====
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 = getBackgroundInfo(el);
if (info) {
tempParams = { ...info };
}
updatePanelContent(el);
realtimeRender(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) {
console.log('🔄 检测到URL变化:', currentUrl);
lastUrl = currentUrl;
setTimeout(() => {
applyStoredData();
}, 500);
}
}
// ===== 主操作框UI =====
function createFloatingBall() {
if (floatingBall) return;
floatingBall = document.createElement('div');
floatingBall.id = 'bg-magician-ball';
floatingBall.textContent = '🎨';
floatingBall.title = '打开网页渲染修改JS';
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;
}
#bg-magician-ball:hover {
background: #5a5a7a;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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-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>网页渲染修改JS <span style="font-size:11px;color:#666;">v1.0</span></h2>
<button class="panel-close" id="bg-panel-close">✕</button>
</div>
<div id="bg-panel-content">
<div class="param-group">
<label>背景媒体 URL <span style="color:#888;font-weight:normal;">(图片或视频)</span></label>
<input type="text" id="bg-image-input" placeholder="输入图片URL 或 视频URL (mp4/webm等)" />
<div style="font-size:10px;color:#666;margin-top:3px;">
支持: 图片 (jpg/png/gif/svg) 或 视频 (mp4/webm/ogg/mov)
</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>背景透明度 <span style="color:#888;font-weight:normal;">(仅背景)</span></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="fp-status" id="fp-status-text">输入媒体URL,点击应用为全网页背景</div>
</div>
<div class="status-text" id="bg-status-text">💡 DOM树位置模式:通过元素在DOM树中的唯一路径定位</div>
</div>
`;
document.body.appendChild(panelElement);
// ===== 事件绑定 =====
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);
}
removeVideoBackground(activeElement);
realtimeRender(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);
realtimeRender(activeElement, tempParams);
document.getElementById('bg-status-text').textContent = '✅ 已保存数据!';
setTimeout(() => {
document.getElementById('bg-status-text').textContent = '💡 DOM树位置模式:通过元素在DOM树中的唯一路径定位';
}, 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();
removeFullPageBackground();
applyFullPageBackground(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('确定要取消全网页背景吗?')) {
removeFullPageBackground();
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 = '💡 DOM树位置模式:通过元素在DOM树中的唯一路径定位';
}, 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 = getBackgroundInfo(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();
}
}
// ===== DOM变化监听 =====
function setupMutationObserver() {
const observer = new MutationObserver(function(mutations) {
for (const [selector, params] of elementDataMap) {
if (selector === 'body' && params.isFullPage) continue;
const elements = findAllElementsBySelector(selector);
if (elements.length > 0) {
for (const el of elements) {
const computed = getComputedStyle(el);
const bgImage = computed.backgroundImage;
if (params.bgImage && params.bgImage.trim() !== '' &&
(bgImage === 'none' || bgImage === '')) {
console.log('🔄 DOM变化检测到元素,重新渲染:', selector);
realtimeRender(el, params);
}
}
}
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
return observer;
}
// ===== 初始化 =====
if (document.readyState === 'complete') {
init();
} else {
window.addEventListener('load', init);
}
function init() {
console.log('📦 初始化...');
loadFromStorage();
cleanupOldData();
createPanel();
createFloatingBall();
applyStoredData();
domObserver = setupMutationObserver();
setInterval(checkUrlChange, 500);
if (panelElement) {
panelElement.classList.remove('visible');
isPanelVisible = false;
}
if (floatingBall) {
floatingBall.style.display = 'flex';
}
document.body.style.marginRight = '0';
console.log('✅ 网页渲染修改JS v1.0 初始化完成!');
console.log('💡 DOM树位置模式:通过元素在DOM树中的唯一路径定位');
}
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: removeFullPageBackground,
isFullPageActive: () => isFullPageActive,
clearAll: function() {
elementDataMap.clear();
removeFullPageBackground();
saveToStorage();
console.log('🗑️ 已清除所有数据');
}
};
})();