有时候我们会碰到这样的需求,切换页面的风格主题啊,例如白天模式,或者晚上模式啊,还有各种各样鲜艳的背景主题啊,接下来我们来看看到底该如何去实现它。
1. 切换类名来更改主题
<!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>
.bodyBac{
background-color: rgb(56, 205, 96);
}
.night{
background-color: black;
}
.day{
background-color: white;
}
</style>
</head>
<body class="bodyBac">
<button onclick="beNight()">夜间</button>
<button onclick="beDay()">白天</button>
<script>
function beNight() {
document.body.className = 'night'
}
function beDay() {
document.body.className = 'day'
}
</script>
</body>
</html>
2. 通过切换link标签的href
<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">
<!-- <link rel="stylesheet" href="./day.css"> -->
<title>Document</title>
</head>
<body>
<button onclick="beDay()">白天</button>
<button onclick="beNight()">黑夜</button>
<script>
let link = document.createElement('link')
function beDay() {
link.rel="stylesheet"
link.href = './dark.css'
document.head.appendChild(link)
}
function beNight() {
link.href = './day.css'
}
</script>
</body>
3. css预处理,less,定义全局变量