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

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.效果展示(以谷歌首页为例)


前端判断系统主题

 

 前端判断系统主题

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-15
  • 2021-11-04
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案