如何通过按钮为网站启用深色主题



如何允许用户在不使用任何第三方库的情况下切换到页面暗主题?(这个问题的答案只提供外部库,但我想在没有它们的情况下完成。(

:root {
--bg-color: #cfd8dc;
--text-color: #212121;
}
[data-theme="dark"] {
--bg-color: #263238;
--text-color: #e0e0e0;
}
body {
color: var(--text-color);
background-color: var(--bg-color); 
font-family: "Playfair Display";
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 80vh;
}
.toggle-button {
-webkit-appearance: none;
outline: none;
width: 200px;
height: 100px;
background-color: #212121;
border-radius: 50px;
position: relative;
transition: .4s;
}
.toggle-button:before{
content: "";
position: absolute;
height: 100px;
width: 100px;
border-radius: 50px;
top: 0;
bottom: 0;
background-color: #bdbdbd;
transition: .4s;
}
.toggle-button:checked {
background-color: #bdbdbd;
}
.toggle-button:checked:before {
transform: translate(100%);
background-color: #212121;
transition: .4s;
}
<script>
const toggleSwitch = document.querySelector('.toggle-button');
function switchTheme(e) {
if(e.target.checked) {
document.documentElement.setAttribute('data-theme', 'dark');
} else {
document.documentElement.setAttribute('data-theme', 'light');
}
}
toggleSwitch.addEventListener('change', switchTheme, false);
</script>
<nav>
<h1>Light Theme/Dark Theme Selector</h1>
</nav>
<div class="container">
<h2 style="margin-right:20px">Light</h2>
<input type="checkbox" class="toggle-button">
<h2 style="margin-left:20px;">Dark</h2>
</div>

如果您希望它允许两种web设计,请在html节点上使用HTML类:

function makeDark() {
document.body.parentNode.classList.remove("light")
document.body.parentNode.classList.add("dark")
}
function makeLight() {
document.body.parentNode.classList.add("light")
document.body.parentNode.classList.remove("dark")
}
.dark {
color: #fff;
background: #012;
}
.light {
color: #000;
background: #def;
}
.dark input {
appearance: none;
background: #000;
color: #fff;
}
<!doctype html>
<html class="dark" lang="en">
<head>
<meta charset=utf8>
<title>Foo</title>
</head>
<body>
<p>Some text</p>
<input value=input text>
<button onclick=makeDark()>Dark</button>
<button onclick=makeLight()>Light</button>
</body>
</html>

然后,您还希望将状态存储在cookie中。

相关内容

  • 没有找到相关文章

最新更新