掘金主题切换器

一键切换掘金网站的黑暗/普通主题

目前為 2025-07-10 提交的版本,檢視 最新版本

// ==UserScript==
// @name         掘金主题切换器
// @namespace    http://tampermonkey.net/
// @version      1.1
// @description  一键切换掘金网站的黑暗/普通主题
// @author       Wangshiwei
// @match        https://juejin.cn/*
// @match        chrome-extension://*/juejin.cn/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=juejin.cn
// @license      MIT
// @grant        GM_setValue
// @grant        GM_getValue
// ==/UserScript==

(function() {
    'use strict';
    // 初始化主题状态
    let isDarkTheme = GM_getValue('isDarkTheme', false);
    // 切换主题函数
    function toggleTheme() {
        isDarkTheme = !isDarkTheme;
        GM_setValue('isDarkTheme', isDarkTheme);
        applyTheme();
    }

    // 应用主题函数
    function applyTheme() {
        const body = document.body;
        if (isDarkTheme) {
            body.classList.remove('light');
            body.classList.add('dark');
            body.setAttribute('data-theme', 'dark');
        } else {
            body.classList.remove('dark');
            body.classList.add('light');
            body.setAttribute('data-theme', 'light');
        }
        updateButtonStyle();
    }

    // 更新按钮样式
    function updateButtonStyle() {
        const button = document.getElementById('juejin-theme-toggle');
        if (button) {
            button.innerHTML = isDarkTheme ? '☀️ ' : '🌙 ';
            button.style.backgroundColor = isDarkTheme ? '#333' : '#f0f0f0';
            button.style.color = isDarkTheme ? '#fff' : '#333';
        }
    }

    // 创建切换按钮
    function createThemeToggleButton() {
        const button = document.createElement('button');
        button.id = 'juejin-theme-toggle';
        button.innerHTML = isDarkTheme ? '☀️亮' : '🌙暗';
        button.style.position = 'fixed';
        button.style.top = '12px';
        button.style.right = '0px';
        button.style.zIndex = '9999';
        button.style.padding = '8px 12px';
        button.style.borderRadius = '4px';
        button.style.border = 'none';
        button.style.cursor = 'pointer';
        button.style.backgroundColor = isDarkTheme ? '#333' : '#f0f0f0';
        button.style.color = isDarkTheme ? '#fff' : '#333';
        button.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.2)';
        button.style.transition = 'all 0.3s ease';

        button.addEventListener('click', toggleTheme);
        document.body.appendChild(button);
    }

    // 初始化
    function init() {
        applyTheme();
        createThemeToggleButton();
    }

    // 页面加载完成后执行
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();