📌  相关文章
📜  javascript 查看 chrome 是否处于暗模式 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:02:40.883000             🧑  作者: Mango

代码示例3
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    // dark mode
}

//To watch for changes:

window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
    const newColorScheme = e.matches ? "dark" : "light";
});

//Or in React Hooks:

const [mode, setMode] = useState<"light" | "dark" | undefined>(
    window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? "dark" :"light"
);

useEffect(() => {
  const modeMe = (e: any) => {
    setMode(e.matches ? "dark" : "light");
  }  
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', modeMe);
  return window.matchMedia('(prefers-color-scheme: dark)').removeListener(modeMe);
}, []);