修改radio单选框样式
前言
在使用表单元素单选框的时候,根据需求可能需要修改默认的单选框样式
效果图
一、样式改动思路
隐藏掉单选框input的默认样式,然后在label前面加上自定义的伪元素
二、通过js绑定label和input关系
input单选框选中是标签属性checked控制的,通过DOM操作,改变元素的checked属性值,做到绑定的效果
三、完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
div>input {
display: none;
}
div>label {
position: relative;
margin-right: 34px;
}
div>label::before {
display: inline-block;
content: "";
width: 16px;
height: 16px;
border-radius: 50%;
border: 1px solid rgb(219, 219, 219);
margin-right: 6px;
vertical-align: bottom;
}
div>input:checked+label::before {
background-color: rgb(239, 66, 56);
}
div>input:checked+label::after {
display: inline-block;
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
position: absolute;
left: 6px;
bottom: 6px;
background-color: white;
}
</style>
</head>
<body>
<div>
<div class="radiobox" onclick="label(event)">
<input type="radio" name="paixu" checked />
<label style="cursor: pointer" @click="点击">按热门排序</label>
</div>
<div class="radiobox" onclick="label(event)">
<input type="radio" name="paixu" />
<label style="cursor: pointer">按评价排序</label>
</div>
<div class="radiobox" onclick="label(event)">
<input type="radio" name="paixu" />
<label style="cursor: pointer">按时间排序</label>
</div>
</div>
</body>
<script type="text/javascript">
function label(e) {
if (e.target.tagName === "LABEL") {
const arr = document.querySelectorAll("input");
arr.forEach((item) => {
item.checked = false;
});
e.target.previousElementSibling.checked = true;
console.log(e.target.previousElementSibling, "555");
}
if (e.target.tagName === "INPUT") { }
console.log(e);
console.log(e.target);
}
</script>
</html>