这篇文章将为大家详细讲解有关使用纯CSS实现电源开关控件的方法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。


https://github.com/comehope/front-end-daily-challenges
定义 dom,包含 3 个元素,分别代表 input 控件、开关和灯光:
居中显示:
body {
margin: 0;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background-color: #eee;
}定义控件的样式,把控件的设置为透明,使其不可见,但仍可与用户交互。其中字号大小是变量,因为 input 控件的字号与正文字号不同,所以需要单独设置:
body {
font-size: var(--font-size);
}
:root {
--font-size: 16px;
}
.toggle {
position: absolute;
font-size: var(--font-size);
width: 5em;
height: 8em;
margin: 0;
filter: opacity(0);
cursor: pointer;
z-index: 2;
}设置开关的轮廓:
.switch {
position: absolute;
width: 5em;
height: 8em;
border-radius: 1.2em;
background: linear-gradient(#d2d4d6, white);
}用阴影使开关变得立体:
.switch {
box-shadow:
inset 0 -0.2em 0.4em rgba(212, 212, 212, 0.75),
inset 0 -0.8em 0 0.1em rgba(156, 156, 156, 0.85),
0 0 0 0.1em rgba(116, 116, 116, 0.8),
0 0.6em 0.6em rgba(41, 41, 41, 0.3),
0 0 0 0.4em #d4d7d8;
}用伪元素设置 on 和 off 文本,目前是处于 off 状态:
.toggle ~ .switch::before,
.toggle ~ .switch::after {
position: absolute;
width: 100%;
text-align: center;
font-size: 1.4em;
font-family: sans-serif;
text-transform: uppercase;
}
.toggle ~ .switch::before {
content: '|';
bottom: 1em;
color: rgba(0, 0, 0, 0.5);
text-shadow: 0 0.1em 0 rgba(255, 255, 255, 0.8);
}
.toggle ~ .switch::after {
content: 'O';
top: 0.6em;
color: rgba(0, 0, 0, 0.45);
text-shadow: 0 0.1em 0 rgba(255, 255, 255, 0.4);
}把 input 控件设置为 checked状态,以便设置处于 on 状态的样式:
设置处于 on 状态的开关样式:
.toggle:checked ~ .switch {
background: linear-gradient(#a1a2a3, #f0f0f0);
box-shadow:
inset 0 0.2em 0.4em rgba(212, 205, 199, 0.75),
inset 0 0.8em 0 0.1em rgba(255, 255, 255, 0.77),
0 0 0 0.1em rgba(116, 116, 118, 0.8),
0 -0.2em 0.2em rgba(41, 41, 41, 0.18),
0 0 0 0.4em #d4d7d8;
}设置处于 on 状态的文本样式:
.toggle:checked ~ .switch::before {
bottom: 0.3em;
text-shadow: 0 0.1em 0 rgba(255, 255, 255, 0.5);
}
.toggle:checked ~ .switch::after {
top: 1.2em;
text-shadow: 0 0.1em 0 rgba(255, 255, 255, 0.15);
}接下来设置灯光效果。
先设置处于 off 状态的黑暗效果:
.toggle ~ .light {
width: 100vw;
height: 100vh;
background-color: #0a0a16;
z-index: 1;
filter: opacity(0.7);
}再设置处于 on 状态的明亮效果:
.toggle:checked ~ .light {
filter: opacity(0);
}关于使用纯CSS实现电源开关控件的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。