最近有个需求关于网站换皮肤,大致看了一遍别人的方案,自己实操总结了一下
一种是切换主题css,准备好几套主题css,无论是直接更改link引入,还是追加类名,这种方案适用于有固定的样式风格的需求,都需要提前准备好备用的几套主题css文件
类似下面这种 ,切换href资源,或者动态插入link标签
<link href="./dark.css" rel="stylesheet">
<link href="./light.css" rel="stylesheet">
或者
给外层追加类名,动态切还样式
<body class='dark light'>
</body>
好处是,方案实现简单,尤其现在都是ui库玩的,你可以让ui去配几个主题导出来,到时候无非是切换引入不同的主题样式就行了
还有一种采用css变量,自己去定义一套css变量适配,相对来说较麻烦一点,毕竟你需要去给你需要用到控制变量的地方都要进行绑定,但优点是自己控制,颗粒度都可以很细,无论less sass
下面是用css实现的简单例子
<!-- index.html -->
<!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: 0;
padding: 0;
-webkit-box-sizing: border-box;
box-sizing: border-box;
font-size: 16px;
}
:root {
--theme__color: white;
--theme_back_color: white;
--theme_btn: black;
}
head,
body {
width: 100vw;
height: 100vh;
overflow: hidden;
color: var(--theme__color);
background-color: var(--theme_back_color);
}
button {
cursor: pointer;
width: 96px;
height: 32px;
border: 0px;
margin-top: 20px;
border-radius: 4px;
background-color: var(--theme_btn);
font-size: 14px;
color: var(--theme__color);
}
</style>
<script>
// index.js
window.onload = function() {
const changeTheme = document.getElementById('changeTheme');
//配置的css变量
const ThemeSwitch = {
style: {
'--theme__color': 'red',
'--theme_back_color': 'red',
}
}
//随机颜色
function rgb() { //rgb颜色随机
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r},${g},${b})`;
}
changeTheme.addEventListener('click', (e) => {
// 给个随机色值
let randomRgb = rgb()
Object.keys(ThemeSwitch.style).reduce((acc, item) => {
document.styleSheets[0].cssRules[0].style.setProperty(item, randomRgb)
}, [])
})
}
</script>
</head>
<body>
<div>
<button id="changeTheme">切换主题风格</button>
</div>
</body></html>