How do I detect dark mode using JavaScript?

后端 未结 3 1096
庸人自扰
庸人自扰 2020-11-28 23:55

Windows and macOS now have dark mode.

For CSS I can use:

    @media (prefers-dark-interface) { 
      color:          


        
相关标签:
3条回答
  • 2020-11-29 00:35

    According to MediaQueryList - Web APIs | MDN, addListener is the correct way to listen to the change. addEventListener is not working for me on iOS 13.4.

    window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
      console.log(`changed to ${e.matches ? "dark" : "light"} mode`)
    });
    
    0 讨论(0)
  • 2020-11-29 00:40
    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";
    });
    
    0 讨论(0)
  • 2020-11-29 00:45

    You can check the CSS Media-Queries directly with Javascript

    The window.matchMedia() method returns a MediaQueryList object representing the results of the specified CSS media query string. The value of the matchMedia() method can be any of the media features of the CSS @media rule, like min-height, min-width, orientation, etc.

    To check if the Media-Query is true the matches property can be used

    // Check to see if Media-Queries are supported
    if (window.matchMedia) {
      // Check if the dark-mode Media-Query matches
      if(window.matchMedia('(prefers-color-scheme: dark)').matches){
        // Dark
      } else {
        // Light
      }
    } else {
      // Default (when Media-Queries are not supported)
    }
    

    To update the color-scheme dynamically if the user would change their preference the following can be used:

    function setColorScheme(scheme) {
      switch(scheme){
        case 'dark':
          // Dark
          break;
        case 'light':
          // Light
          break;
        default:
          // Default
          break;
      }
    }
    
    function getPreferredColorScheme() {
      if (window.matchMedia) {
        if(window.matchMedia('(prefers-color-scheme: dark)').matches){
          return 'dark';
        } else {
          return 'light';
        }
      }
      return 'light';
    }
    
    if(window.matchMedia){
      var colorSchemeQuery = window.matchMedia('(prefers-color-scheme: dark)');
      colorSchemeQuery.addEventListener('change', setColorScheme(getPreferedColorScheme()));
    }
    
    0 讨论(0)
提交回复
热议问题