Detect dark mode using JavaScript

被刻印的时光 ゝ 提交于 2019-12-10 13:52:21

问题


Windows and macOS now have dark mode.

For CSS I can use:

@media (prefers-dark-interface) { 
  color: white; background: black 
}

But I am using the Stripe ELements API, which puts colors in JavaScript

For example:

  const stripeElementStyles = {
    base: {
      color: COLORS.darkGrey,
      fontFamily: `-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"`,
      fontSize: '18px',
      fontSmoothing: 'antialiased',
      '::placeholder': {
        color: COLORS.midgrey
      },
      ':-webkit-autofill': {
        color: COLORS.icyWhite
      }
    }
  }

How can I detect the OS's preferred color scheme in JavaScript?


回答1:


if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    // dark mode
}


来源:https://stackoverflow.com/questions/56393880/detect-dark-mode-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!