静态页换肤
红背景黄背景
代码:
<!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>
:root{
--background-color:red;
}
html,body{
width:100%;
height:100%;
padding:0;
margin:0;
}
body{
background-color: var(--background-color);
}
.switch-input{
display:none;
}
.switch-label{
display:inline-block;
width:50px;
height:24px;
border:1px solid grey;
border-radius:24px;
position:relative;
padding:1px;
box-sizing: border-box;
}
.switch-label::after{
display: inline-block;
content:'';
width:50%;
height:20px;
background-color: blue;
position:absolute;
left:0;
border-radius:20px;
transition: all .2s ease-in;
}
.switch-input:checked + .switch-label::after{
left:50%;
transform: rotate(360deg);
}
</style>
</head>
<body>
<input type="checkbox" id="switch-box" class="switch-input" />
<label for="switch-box" class="switch-label"></label>
<script>
document.querySelector('#switch-box').addEventListener('click',()=>{
document.documentElement.style.setProperty('--background-color','yellow')
})
</script>
</body>
</html>
换肤组件
ToggleFace
import react,{useEffect} from 'react'
import './toggleFace.css'
//初始化变量名和值
// {
// '--bgcolor':'red'
// }
/*
<style>
:root{
'--bgcolor':'red'
}
</style>
*/
//切换颜色的方法
interface ToggleFaceFC{
initColorKey:object;
changeVar:(key:string,value:string)=>void
}
export default function ToggleFace(props:ToggleFaceFC){
useEffect(()=>{
let styleStr = `:root{`
for(let key in props.initColorKey){
styleStr+=key+':'+props.initColorKey[key]+';\n'
}
styleStr+='}'
let styleDom = document.createElement('style')
styleDom.innerHTML=styleStr
document.head.appendChild(styleDom)
},[])
return <>
<input type="checkbox" id="switch-box" className="switch-input" onClick={props.changeVar} />
<label for="switch-box" className="switch-label"></label>
</>
}
toggleFace.css
.switch-input{
display:none;
}
.switch-label{
display:inline-block;
width:50px;
height:24px;
border:1px solid grey;
border-radius:24px;
position:relative;
padding:1px;
box-sizing: border-box;
}
.switch-label::after{
display: inline-block;
content:'';
width:50%;
height:20px;
background-color: blue;
position:absolute;
left:0;
border-radius:20px;
transition: all .2s ease-in;
}
.switch-input:checked + .switch-label::after{
left:50%;
transform: rotate(360deg);
}
网友评论