【发布时间】:2021-12-04 02:35:21
【问题描述】:
我制作了一个明暗切换按钮,我想为其添加明暗功能。按下此开关,页面应在暗模式和亮模式之间切换其主题。开关添加了一些基本样式,使其在切换时显示浅色或深色主题。
<body>
<div class="theme-toggle" style="cursor: pointer;">
<input type="checkbox" checked style="cursor: pointer;">
<div class="toggle-body" style="cursor: pointer;"></div>
<div class="celestial-body" style="cursor: pointer;"></div>
</div>
<style>
:root {
--width: 60px;
--height: 30px;
}
body {
font-family: monaco, sans-serif;
box-sizing: border-box;
margin: 0;
padding: 0;
margin: 2em;
}
.theme-toggle {
position: relative;
width: var(--width);
height: var(--height);
}
.theme-toggle input[type="checkbox"] {
position: absolute;
top: 0;
left: 0;
opacity: 0;
z-index: 1;
width: var(--width);
height: var(--height);
}
.theme-toggle .toggle-body {
position: absolute;
top: 0;
left: 0;
width: var(--width);
height: var(--height);
border: 2px solid #080808;
border-radius: var(--height);
transition: all 80ms ease-in-out;
}
.theme-toggle input[type="checkbox"]~.toggle-body {
background: #1d1d1d;
background-image: url("https://cdn.glitch.com/9be3ef5e-cf68-4fac-9bd5-82714468aed6%2F1e7b6b11b5b398711c60f2b71cdf9b03.gif?v=1599237363310");
background-size: cover;
}
/*
https://i.giphy.com/media/U3qYN8S0j3bpK/giphy.webp
*/
.theme-toggle input[type="checkbox"]:checked~.toggle-body {
background: #82dfff/*#EDBCD4*/
;
background-image: url("");
background-size: cover;
border-color: #89cbf9/*#CAAAB7*/
;
}
/*
https://i.giphy.com/media/tQgB6lM6XCle8/giphy.webp
*/
.theme-toggle input[type="checkbox"]~.celestial-body {
position: absolute;
width: 24px;
height: 24px;
border: 2px solid #fff08e/*white*/
;
border-radius: 100%;
background: #fff5c4/*#F0F0FA*/
;
transition: all 80ms ease-in-out;
}
.theme-toggle input[type="checkbox"]:not(:checked)~.celestial-body {
top: 3px;
left: 3px;
}
.theme-toggle input[type="checkbox"]:checked~.celestial-body {
top: 3px;
left: calc(100% - 27px);
background: #ff9900/*#F2E9BD*/
;
border-color: #ddceb1;
}
.theme-toggle input[type="checkbox"]~.celestial-body::after {
content: " ";
opacity: 0;
position: absolute;
left: -20px;
transition: left 0.13s ease-in, opacity 0.15s ease-out;
}
.theme-toggle input[type="checkbox"]:checked~.celestial-body::after {
content: "";
position: absolute;
bottom: -2px;
left: -10px;
display: block;
opacity: 1;
width: 20px;
height: 20px;
background: url("https://cdn.glitch.com/9be3ef5e-cf68-4fac-9bd5-82714468aed6%2FVector%201%20(1).svg?v=1599249814204");
background-size: contain;
background-position: left;
background-repeat: no-repeat;
}
</style>
</body>
您也可以在JSFiddle 上看到此代码
我为我的网站使用的明/暗功能,onclick() 更改为明/暗模式。
【问题讨论】:
标签: javascript html css togglebutton