方法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>一键换肤</title>
<style>
:root {
--color: white;
}
.card {
width: 120px;
height: 200px;
}
.controller {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
}
.btn {
border: none;
height: 30px;
width: 100px;
color: #eeeeee;
background: linear-gradient(45deg, #ce7777, lightblue, #c19fc1, transparent);
border-radius: 999px;
box-shadow: 0 0 2px 2px #eeeeee;
cursor: pointer;
}
.card {
border-radius: 5px;
box-shadow: 0 0 2px 2px rgb(126, 124, 124);
}
.card:nth-child(1) {
background: black;
}
.card:nth-child(3) {
background: white;
}
html, body {
background: var(--color);
opacity: 0.9;
}
body {
height: 100vh;
}
*{
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div class="controller">
<div class="card"></div>
<div><button class="btn" onclick="changeSkin()">一键换肤</button></div>
<div class="card"></div>
</div>
</body>
</html>
<script>
function changeSkin() {
let oldV = 'white';
let newV = 'black';
let nowColor = document.body.style.getPropertyValue('--color');
if(nowColor == '' || nowColor == oldV) {
document.body.style.setProperty('--color', newV)
}else {
document.body.style.setProperty('--color', oldV)
}
}
</script>
方法2
<!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>change skin</title>
<style id="theme">
:root {
--bgColor: #f00;
}
.skin {
background: var(--bgColor);
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div class="skin"></div>
<button type="button" onclick="changeSkin('black')">change theme</button>
<script>
changeSkin = (theme) => {
console.log("function starts");
document.getElementById("theme").innerHTML = `
:root{--bgColor:${theme};}
.skin {
background: var(--bgColor);
width: 200px;
height: 200px;
}
`
}
</script>
</body>
</html>