How to detect if the OS is in dark mode in browsers?

前端 未结 5 598
醉酒成梦
醉酒成梦 2020-11-30 16:53

Similar to \"How to detect if OS X is in dark mode?\" only for browsers.

Has anyone found if there is a way to detect if the user\'s system is in the new OS X Dark M

5条回答
  •  佛祖请我去吃肉
    2020-11-30 17:41

    If you want to detect it from JS, you can use this code:

    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";
    });
    

提交回复
热议问题