以 windows 系统为例 变换主题颜色浏览器页面会根据主题自动切换相应的颜色
话不多说进入正文
CSS解决方案
css 解决方案需要借助 css3的新特性 prefers-color-scheme 返回 no-preference ( 未知 ) \ light ( 浅色 ) \ dark ( 深色 )
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin:0px;
padding: 0px;
box-sizing: border-box;
}
/* 浅色主题 */
@media(prefers-color-scheme: light){
body{
background: #eee;
color:#222
}
}
/*暗色主题*/
@media(prefers-color-scheme: dark){
body{
background: #222;
color:#eee
}
}
</style>
</head>
<body>
<h1>变换主题色</h1>
</body>
</html>
JS 解决方案
需要借助 window.matchMedia() API 来监听当前主题的变化.
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin:0px;
padding: 0px;
box-sizing: border-box;
}
.light{
background: #eee;
color:#222
}
.dark{
background: #222;
color:#eee
}
</style>
</head>
<body>
<h1>变换主题色</h1>
</body>
</html>
<script>
let theme = window.matchMedia("(prefers-color-scheme: light)")
let body = document.getElementsByTagName("body")[0]
if(theme.matches){body.className = "light"}
theme.onchange = (data)=>{
console.log(data.matches,body)
if(data.matches){
body.className = "light"
}else{
body.className = "dark"
}
}
</script>