Dark++

CSS 实现夜间模式; 代码是从贴吧抄的, 嗯 ... over; 由于该实现本质上是覆盖一层, 可能会有未知问题出现: 如 sortTable.js 拖拽无效

  1. // ==UserScript==
  2. // @name Dark++
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.0
  5. // @description CSS 实现夜间模式; 代码是从贴吧抄的, 嗯 ... over; 由于该实现本质上是覆盖一层, 可能会有未知问题出现: 如 sortTable.js 拖拽无效
  6. // @description v0.5 增加 file://* 协议支持
  7. // @description v0.6 通过修改 run-at: docuemnt-body 实现无感知增加遮罩层
  8. // @description v0.7 增加延迟设置, 应对延迟载入内容的页面
  9. // @description v0.8 修复因精度问题导致的透明度设置无效的问题
  10. // @description v1.0 增加亮度同步功能, 在单个页面修改后在所有页面生效
  11. // @icon https://gss0.baidu.com/7Ls0a8Sm2Q5IlBGlnYG/sys/portraith/item/feb81406?t=1435668917
  12. // @author sven
  13. // @include https://*
  14. // @include http://*
  15. // @include file://*
  16. // @match .*
  17. // @grant GM_getValue
  18. // @grant GM_setValue
  19. // @grant GM_addValueChangeListener
  20. // @run-at document-body
  21. // ==/UserScript==
  22.  
  23. (function () {
  24. 'use strict';
  25. const LOCAL_OPACITY_FIELD_NAME = 'dark_model_opacity' // 保存到本地的亮度 key
  26. const m = document.createElement('div')
  27. m.style.zIndex = '999999'
  28. m.style.position = 'absolute'
  29. m.style.height = '100vh'
  30. m.style.width = '100vw'
  31. m.style.position = 'fixed'
  32. m.style.top = '0'
  33. m.style.left = '-9999px'
  34. m.id = 'dark-modal'
  35. let opacity = GM_getValue(LOCAL_OPACITY_FIELD_NAME) || 0.4
  36. const step = 0.05
  37. const updateOpacity = opacityVal => m.style.outline = `rgba(0, 0, 0, ${opacity = opacityVal}) solid 10000px`
  38. const setOpacity = ({ opa, add, sub } = {}) => {
  39. let _opa = Number(opa || opacity) || 0
  40. _opa = add
  41. ? _opa + step
  42. : (sub ? (_opa - step) : _opa)
  43. _opa = Math.max(0, _opa)
  44. _opa = Math.min(1, _opa)
  45. GM_setValue(LOCAL_OPACITY_FIELD_NAME, _opa.toFixed(2))
  46. console.log('%c[Dark++ plugin] %copacity: ' + _opa.toFixed(2), 'color: teal;', 'color: #FFF;')
  47. updateOpacity(_opa)
  48. }
  49. const init = () => {
  50. let delay = localStorage.getItem('DARK_PLUS_PLUS_DELAY')
  51. if (delay === null) {
  52. document.body.append(m)
  53. setOpacity()
  54. } else {
  55. delay = Number(delay)
  56. delay = (isNaN(delay) || delay < 0 || !Number.isInteger(delay)) ? 0 : delay
  57. setTimeout(() => {
  58. document.body.append(m)
  59. setOpacity()
  60. }, delay)
  61. }
  62. // 增加监听函数, 当其他页面修改亮度时在当前页面同步更新
  63. GM_addValueChangeListener(LOCAL_OPACITY_FIELD_NAME, (name, oldVal, val) => updateOpacity(val))
  64. console.log(`%c[Dark++ plugin] delay: ${delay} | %c设置延迟载入遮罩层: %clocalStorage.setItem('DARK_PLUS_PLUS_DELAY', 200)`, 'color: teal', 'color: #FFF', 'color: #AAA')
  65. }
  66. const keyMap = {
  67. 81: () => setOpacity({ add: true }),
  68. 87: () => setOpacity({ sub: true })
  69. }
  70. init()
  71. document.addEventListener('keydown', evt => {
  72. keyMap[evt.keyCode] && keyMap[evt.keyCode](evt)
  73. })
  74. })();