Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
615 views
in Technique[技术] by (71.8m points)

macos darkmode - How do I detect dark mode using JavaScript?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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";
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...