效果示例图
代码块
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>使用css的伪类实现复选框样式修改</title>
<style type="text/css">
.checkbox {
border: 1px solid red;
position: relative;
/* user-select 属性规定是否能选取元素的文本。 */
user-select: none;
cursor: pointer;
}
.checkbox input[type='checkbox'] {
opacity: 0;
}
/* ::before|::after 伪元素 */
.checkbox span::before,
.checkbox span::after {
content: "";
position: absolute;
width: 13px;
height: 13px;
border: 1px solid #00a2ef;
left: 3px;
top: 3px;
border-radius: 4px;
}
.checkbox span::after {
background-color: #00a2ef;
opacity: 0;
}
/* :checked 伪类 */
.checkbox input:checked~span::after {
opacity: 1;
}
.checkbox input:checked~span::before {
opacity: 0;
}
</style>
</head>
<body>
<label class="checkbox">
<input type="checkbox" />
<span>同意并已经阅读该协议</span>
</label>
<div id="btn">ok</div>
</body>
<script type="text/javascript">
document.querySelector("#btn").addEventListener("click", () => {
console.log("[ok]", document.querySelector("input[type='checkbox']").checked)
})
</script>
</html>