Skip to content

Judge system theme by JavaScript

Published: at 03:03 PM

js判断系统主题:让网页适应系统主题及夜间模式

让网页适应系统主题及夜间模式。

1.使用CSS判断 使用媒介查询prefers-color-scheme,支持dark,light,no-preference三种模式。

/*深色*/
@media (prefers-color-scheme: dark) {
    body {
        background: rgb(53, 54, 58);
        color: rgba(238,238,238,1);
    }
}

/*浅色*/
@media (prefers-color-scheme: light) {
    body {
        background: rgb(255,255,255);
        color: rgba(51,51,51,1);
    }
}

2.js判断

/*判断是否支持主题色*/

if (window.matchMedia('(prefers-color-scheme)').media === 'not all') {
    console.log('Browser doesn\\'t support dark mode');
}

/*判断是否处于深色模式*/
if(window.matchMedia('(prefers-color-scheme: dark)').matches){
    //Do some thing
}

/*判断是否处于浅色模式*/
if(window.matchMedia('(prefers-color-scheme: light)').matches){
    //Do some thing
}

/*模式切换听器*/
var listeners={
    dark: function(mediaQueryList ){
        if(mediaQueryList.matches){
            alert('您切换到深色模式了!')
        }
    },
    light: function(mediaQueryList){
        if(mediaQueryList.matches){
            alert('您切换到浅色模式了!')
        }
    }
}

window.matchMedia('(prefers-color-scheme: dark)').addListener(listeners.dark)
window.matchMedia('(prefers-color-scheme: light)').addListener(listeners.light)

3.效果展示(以谷歌首页为例)

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/eb38ae63-56cf-431c-a34e-ab505abfb6e3/1033316-20200528120640792-1912630542.png

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/ab95cc12-e6d9-40b0-9ffb-8091ee164aea/1033316-20200528120915480-102013493.png