前端实现背景模式的切换
1. 具体知识点
-
单选框
-
css变量
-
操作dom修改样式
2. 单选框的实现
<input type="radio" name="pink-theme" id="pink" />
<label for="pink">粉色主题</label>
3.css 变量
var() 函数用于插入 CSS 变量的值。
var() 函数的语法如下:
var(name, value)
值 | 描述 |
---|---|
name | 必需,变量名(以两条破折号开头) |
value | 可选,回退值(在未找到变量时使用) |
变量名称必须以两个破折号(–)开头,且区分大小写!
4.操作dom选择指定的选择器
querySelectorAll方法的官网链接:querySelectorAll
返回与指定的选择器组匹配的文档中的元素列表 (使用深度优先的先序遍历文档的节点)。返回的对象是NodeList。
5.flex实现子元素左右间距相等
display: flex;
justify-content: space-evenly;
6.dom修改样式
document.body.className = "pink-theme";
7.具体代码
<!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>
body {
color: var(--text-color);
background-color: var(--bg-color);
}
.pink-theme {
--bg-color: rgb(193, 126, 126);
--text-color: rgb(42, 34, 34);
--content-text-color: rgb(45, 82, 84);
}
.yellow-theme {
--bg-color: rgb(246, 230, 8);
--text-color: rgb(19, 15, 4);
--content-text-color: rgb(97, 111, 59);
}
.black-theme {
--bg-color: rgb(58, 53, 53);
--text-color: rgb(167, 13, 13);
--content-text-color: rgb(0, 7, 7);
}
.content {
height: 500px;
width: 800px;
margin: auto;
}
.header-box {
height: 50px;
width: 50%;
/* background-color: rgb(166, 172, 152); */
margin: auto;
display: flex;
/*子元素左右间距相等*/
justify-content: space-evenly;
}
.text-box {
height: 300px;
width: 100%;
background-color: var(--content-text-color);
text-align: center;
font-size: 30px;
border-radius: 10px;
}
label {
height: 40px;
width: 80px;
text-align: center;
line-height: 40px;
border-radius: 8px;
background-color: rgb(220, 220, 233);
color: black;
cursor: pointer;
}
/*隐藏单选框*/
label input {
display: none;
}
.theme-button {
border-radius: 8px;
background-color: rgb(220, 220, 233);
}
label input:checked + div {
background-color: rgb(185, 109, 77);
}
</style>
</head>
<body>
<div class="content">
<div class="header-box">
<label for="pink">
<input
type="radio"
id="pink"
name="theme"
value="pink-theme"
checked
/>
<div class="theme-button">粉色模式</div>
</label>
<label for="yellow">
<input type="radio" id="yellow" name="theme" value="yellow-theme" />
<div class="theme-button">黄色模式</div>
</label>
<label for="black">
<input type="radio" id="black" name="theme" value="black-theme" />
<div class="theme-button">黑色模式</div>
</label>
</div>
<div class="text-box">总有人间一两风 填你十万八千梦</div>
</div>
</body>
<script>
document
.querySelectorAll(".header-box input[name=theme]")
.forEach((radio) => {
radio.onchange = function () {
document.body.className = radio.value;
};
});
document.body.className = "pink-theme";
</script>
</html>