演示
原理
本文要实现的按钮大致示意如下:
观察者从正上方观看,写代码时主要处理光照以及近大远小等现象。
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>拟物风格复选按钮</title>
<style>
* {
padding: 0;
margin: 0;
user-select: none;
}
html,
body {
height: 100vh;
}
</style>
<style>
body {
display: flex;
background-color: #181818;
align-items: center;
justify-content: center;
}
/* 按钮区域 */
.chk {
position: relative;
height: 100px;
width: 100px;
border-radius: 50%;
background: #000000;
box-shadow: 0 0 0 2px rgba(0, 0, 0, 1);
}
/* 隐藏默认checkbox */
.chk>input {
appearance: none;
}
/* 按钮本身 */
.chk>span {
position: absolute;
width: 100%;
height: 100%;
border-radius: 50%;
background: #222222;
box-shadow: 0 2px 8px rgba(0, 0, 0, 1),
inset 0 -2px 4px rgba(0, 0, 0, 1),
inset 0 2px 4px rgba(255, 255, 255, 0.5);
transition: 0.2s;
}
/* 按钮按下后因高度下降造成的缩放 */
.chk>input:checked~span {
box-shadow: 0 1px 4px rgba(0, 0, 0, 1),
inset 0 -1px 2px rgba(0, 0, 0, 1),
inset 0 1px 2px rgba(255, 255, 255, 0.5);
transform: scale(0.95);
transition: 0.2s;
}
/* 按钮中间图形 */
.chk>svg {
position: absolute;
width: 100%;
height: 100%;
border-radius: 50%;
stroke: #111111;
stroke-width: 6px;
stroke-linecap: round;
transition: 0.2s;
transition-delay: 0.1s;
}
/* 按钮按下后中间图形点亮 */
.chk>input:checked~svg {
stroke: #00ffff;
filter: drop-shadow(0 0 12px #00ffff);
transform: scale(0.95);
transition: 0.2s;
transition-delay: 0.1s;
}
</style>
</head>
<body>
<!-- 使用label包裹,可以使内部所有元素和checkbox联动 -->
<label class="chk">
<input type="checkbox">
<span></span>
<svg id="btn-more" viewBox="0 0 100 100">
<line x1="50" y1="25" x2="50" y2="50" />
<circle cx="8" cy="70" r="20" fill="none" stroke-dasharray="90" transform="rotate(-39)" />
</svg>
</label>
</body>
</html>
更多例程
更多例程可以参考下面代码仓库:
https://github.com/NaisuXu/front-end-web-examples