css3自定义变量实现网站换肤功能
css3全局变量
通过在:root选择器中设置变量,这样项目中所有的地方都可以访问到,css3中通过--标识符定义变量,在属性中通过var()引入即可
<!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>网站换肤</title>
<style>
:root {
--main-color: #333;
}
:root[theme='blue'] {
--main-color: blue;
}
:root[theme='red'] {
--main-color: red;
}
.box {
color: var(--main-color);
}
</style>
</head>
<body>
<div onclick="change('default')">默认</div>
<div onclick="change('blue')">蓝色</div>
<div onclick="change('red')">红色</div>
<div class="box">我是字体颜色</div>
</body>
<script>
function change(type) {
document.documentElement.setAttribute("theme", type);
}
</script>
</html>