就是获取html根元素,通过js动态的添加类名.
展示:
html+核心css:
<body>
<div class="menu">
<div class="menu-header">
<h2 class="menu-header-title">Theme</h2>
<div class="theme-switcher">
<input type="radio" id="light-theme" name="themes" checked />
<label for="light-theme">
<span> </i>Light </span>
</label>
<input type="radio" id="dark-theme" name="themes" />
<label for="dark-theme">
<span> </i>Dark </span>
</label>
<input type="radio" id="black-theme" name="themes" />
<label for="black-theme">
<span> </i>Black </span>
</label>
<span class="slider"></span>
</div>
</div>
</div>
</body>
<style>
*,
*:after,
*:before {
box-sizing: border-box;
}
:root {
--c-text-primary: #191919;
--c-text-secondary: #737374;
--c-border-primary: #ccc;
--c-bg-body: #ccc;
--c-bg-primary: #fff;
--c-bg-secondary: #d4d8dd;
--c-bg-button: #fff;
--slider-shadow: inset 0 1px 1px #ddd, 0 2px 3px #ccc;
}
:root.dark-theme {
--c-text-primary: #eee;
--c-text-secondary: #d3d5db;
--c-border-primary: #454545;
--c-bg-primary: #323339;
--c-bg-secondary: #222128;
--c-bg-button: #494a50;
--slider-shadow: inset 0 1px 1px #767676;
}
:root.black-theme {
--c-text-primary: #edeeef;
--c-text-secondary: #d4d7e1;
--c-border-primary: #323232;
--c-bg-primary: #1b1d23;
--c-bg-secondary: #000001;
--c-bg-button: #343844;
--slider-shadow: inset 0 1px 1px #555;
}
body {
font-family: "Inter", sans-serif;
line-height: 1.5;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background-color: var(--c-bg-body);
color: var(--c-text-primary);
}
</style>
javascript:
<script>
var html = document.getElementsByTagName("html");
var radios = document.getElementsByName("themes");
for (i = 0; i < radios.length; i++) {
radios[i].addEventListener("change", function () {
console.log(this);//当前this指向事件的触发者
html[0].classList.remove(html[0].classList.item(0));
html[0].classList.add(this.id);
});
}
</script>