知乎夜间模式

开启知乎夜间模式,并且跟随系统主题自动切换,切换后刷新网页不会出现闪白的情况

目前為 2023-02-18 提交的版本,檢視 最新版本

// ==UserScript==
// @name        知乎夜间模式
// @namespace    http://tampermonkey.net/
// @version      0.3
// @description  开启知乎夜间模式,并且跟随系统主题自动切换,切换后刷新网页不会出现闪白的情况
// @author       Dark15
// @match        *://*.zhihu.com/*
// @grant        none
// @run-at document-end
// ==/UserScript==

;(function () {
  'use strict'
  // 是否是第一次加载
  let isFirstLoad = true

  function isSysDarkMode() {
    // 判断系统主题是否为黑色
    return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
  }

  function isZhihuDarkMode() {
    // 判断知乎网站是否为夜间模式
    return document.documentElement.getAttribute('data-theme') === 'dark'
  }

  function setTheme(theme) {
    // 设置知乎网站的主题,需要刷新页面
    window.location.href = window.location.href.split('?')[0] + '?theme=' + theme
  }

  function setRootTheme(theme) {
    // 设置html根标签的data-theme属性,无需刷新页面
    document.documentElement.setAttribute('data-theme', theme)
  }

  function switchTheme() {
    if (isSysDarkMode()) {
      if (!isZhihuDarkMode()) {
        if (isFirstLoad) {
          setTheme('dark')
        }
        setRootTheme('dark')
      }
    } else {
      if (isZhihuDarkMode()) {
        if (isFirstLoad) {
          setTheme('light')
        }
        setRootTheme('light')
      }
    }
    isFirstLoad = false
  }

  // 初始时切换一次主题
  switchTheme()

  // 监听系统主题变化,切换主题
  const mql = window.matchMedia('(prefers-color-scheme: dark)')

  mql.addEventListener('change', switchTheme)
})()

QingJ © 2025

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