Recently, according to the system theme to determine the theme of the web page scene more and more, the common way is based on CSS media query, CSS media query can not be based on user preferences from the definition of the theme, so this article includes CSS and JS two scenarios.

The CSS uses media query

You can use the preferred-color-scheme media attribute in the CSS.

    @media (prefers-color-scheme: light) {
      body {
        background: #fff;
        color: # 333; }}@media (prefers-color-scheme: dark) {
      body {
        background: # 333;
        color: #fff; }}Copy the code

Javascript detects system themes

Getting system topics

Get a light or dark theme in JavaScript and use the matchMedia function to check if the CSS media query has been satisfied. Check whether the current topic is correct by checking the result matches

    const themeMedia = window.matchMedia("(prefers-color-scheme: light)");
    if (themeMedia.matches) {
        console.log('light')}else {
        console.log('dark')}Copy the code

Listen for topic changes

The preceding method can obtain the theme only once. If the user changes the theme, the page cannot change the theme in real time. Fortunately, the above MediaQueryList object supports the addListener method to listen for topic changes. Through listening can solve the topic switch real-time update of the amount of the problem.

    const themeMedia = window.matchMedia("(prefers-color-scheme: light)");
    themeMedia.addListener(e= > {
        if (e.matches) {
            console.log('light')}else {
            console.log('dark')}});Copy the code