网页颜色动态变化

让网页背景和文字颜色持续变化

目前為 2025-06-15 提交的版本,檢視 最新版本

// ==UserScript==
// @name         网页颜色动态变化
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  让网页背景和文字颜色持续变化
// @author       豆包
// @match        *://*/*
// @grant        none
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';
    
    // 颜色变化间隔时间(毫秒)
    const CHANGE_INTERVAL = 2000;
    // 颜色变化的元素选择器
    const TARGET_ELEMENTS = ['body', 'html'];
    
    // 开始颜色变化
    function startColorCycle() {
        setInterval(changeColors, CHANGE_INTERVAL);
        // 初始化时先执行一次
        changeColors();
    }
    
    // 生成随机颜色
    function getRandomColor() {
        const r = Math.floor(Math.random() * 256);
        const g = Math.floor(Math.random() * 256);
        const b = Math.floor(Math.random() * 256);
        return `rgb(${r}, ${g}, ${b})`;
    }
    
    // 修改页面颜色
    function changeColors() {
        const bgColor = getRandomColor();
        const textColor = getContrastColor(bgColor);
        
        TARGET_ELEMENTS.forEach(selector => {
            const elements = document.querySelectorAll(selector);
            elements.forEach(element => {
                element.style.backgroundColor = bgColor;
                element.style.color = textColor;
            });
        });
    }
    
    // 生成与背景色对比度高的文字颜色
    function getContrastColor(hexColor) {
        // 简化处理:如果是RGB格式先转16进制
        if (hexColor.startsWith('rgb')) {
            const rgb = hexColor.match(/\d+/g).map(Number);
            hexColor = `#${rgb[0].toString(16).padStart(2, '0')}${rgb[1].toString(16).padStart(2, '0')}${rgb[2].toString(16).padStart(2, '0')}`;
        }
        
        // 计算亮度(简化算法)
        const r = parseInt(hexColor.slice(1, 3), 16);
        const g = parseInt(hexColor.slice(3, 5), 16);
        const b = parseInt(hexColor.slice(5, 7), 16);
        const brightness = (r * 299 + g * 587 + b * 114) / 1000;
        
        // 亮度高时用黑色,亮度低时用白色
        return brightness > 125 ? '#000000' : '#FFFFFF';
    }
    
    // 页面加载完成后启动颜色变化
    document.addEventListener('DOMContentLoaded', startColorCycle);
})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址