前端简单换肤(css变量)
代码demo
test.html
// An highlighted block
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CSS varies</title>
<link rel="stylesheet" type="text/css" href="./comon.css" />
<style>
.header {
height: 100px;
background-color: var(--background-color);
}
.title {
color: var(--font-color); /* 用css变量标记颜色 */
}
</style>
</head>
<body>
<div class="header">
<h3 class="title">CSS 变量换肤</h3>
</div>
<input type="color" onblur="changeColor(value)" />
<script>
function changeColor(value) {
let r = parseInt(value.substring(1, 3), 16) * 0.299;
let g = parseInt(value.substring(3, 5), 16) * 0.587;
let b = parseInt(value.substring(5, 7), 16) * 0.114;
let gray = r + g + b;
let color = "white";
if (gray > 200) {
color = "#666";
}
const background = value;
debugger;
document.documentElement.style.setProperty("--font-color", color);
document.documentElement.style.setProperty(
"--background-color",
background
);
}
</script>
</body>
</html>
comon.css
:root {
--font-color: white;
--background-color: blue;
}
实现效果