知乎夜间模式

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

目前为 2023-02-19 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name 知乎夜间模式
  3. // @namespace http://tampermonkey.net/
  4. // @icon https://static.zhihu.com/heifetz/favicon.ico
  5. // @version 0.5
  6. // @description 开启知乎夜间模式,并且跟随系统主题自动切换,切换后刷新网页不会出现闪白的情况
  7. // @author Dark15
  8. // @match *://*.zhihu.com/*
  9. // @grant none
  10. // @run-at document-end
  11. // ==/UserScript==
  12.  
  13. ;(function () {
  14. 'use strict'
  15. // 是否是第一次加载
  16. let isFirstLoad = true
  17.  
  18. function isSysDarkMode() {
  19. // 判断系统主题是否为黑色
  20. return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
  21. }
  22.  
  23. function isZhihuDarkMode() {
  24. // 判断知乎网站是否为夜间模式
  25. return document.documentElement.getAttribute('data-theme') === 'dark'
  26. }
  27.  
  28. function setTheme(theme) {
  29. // 设置知乎网站的主题,需要刷新页面
  30. window.location.href = window.location.href.split('?')[0] + '?theme=' + theme
  31. }
  32.  
  33. function setRootTheme(theme) {
  34. // 设置html根标签的data-theme属性,无需刷新页面
  35. document.documentElement.setAttribute('data-theme', theme)
  36. fetch('/?theme=' + theme)
  37. }
  38.  
  39. function switchTheme() {
  40. const isSysDark = isSysDarkMode()
  41. const isZhihuDark = isZhihuDarkMode()
  42. if ((isSysDark && !isZhihuDark) || (!isSysDark && isZhihuDark)) {
  43. const theme = isSysDark ? 'dark' : 'light'
  44. if (isFirstLoad) {
  45. setTheme(theme)
  46. }
  47. setRootTheme(theme)
  48. }
  49. isFirstLoad = false
  50. }
  51.  
  52. // 初始时切换一次主题
  53. switchTheme()
  54.  
  55. // 监听系统主题变化,切换主题
  56. const mql = window.matchMedia('(prefers-color-scheme: dark)')
  57.  
  58. mql.addEventListener('change', switchTheme)
  59. })()

QingJ © 2025

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