h5 radiobox实现
实现 H5 的单选框(RadioBox)
在 HTML5 中,单选框(RadioBox)通过 <input type="radio"> 标签实现,通常需要配合 <label> 标签提升用户体验。
基本语法
<input type="radio" id="option1" name="group1" value="value1">
<label for="option1">选项1</label>
<input type="radio" id="option2" name="group1" value="value2">
<label for="option2">选项2</label>
name 属性相同的单选框属于同一组,只能选中一个。
value 是提交表单时的值。
for 属性与 id 绑定,点击标签即可选中单选框。
默认选中
通过 checked 属性设置默认选中项:
<input type="radio" id="option1" name="group1" value="value1" checked>
样式自定义
使用 CSS 隐藏原生单选框,通过伪元素自定义样式:
input[type="radio"] {
display: none;
}
input[type="radio"] + label::before {
content: "";
display: inline-block;
width: 16px;
height: 16px;
border: 1px solid #999;
border-radius: 50%;
margin-right: 8px;
}
input[type="radio"]:checked + label::before {
background-color: #007bff;
}
动态获取选中值
通过 JavaScript 获取选中的值:
document.querySelector('input[name="group1"]:checked').value;
示例代码
<!DOCTYPE html>
<html>
<head>
<style>
input[type="radio"] { display: none; }
input[type="radio"] + label::before {
content: "";
display: inline-block;
width: 16px;
height: 16px;
border: 1px solid #999;
border-radius: 50%;
margin-right: 8px;
}
input[type="radio"]:checked + label::before {
background-color: #007bff;
}
</style>
</head>
<body>
<form>
<input type="radio" id="male" name="gender" value="male" checked>
<label for="male">男</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">女</label>
</form>
<script>
document.querySelector('form').addEventListener('change', function() {
const selectedValue = document.querySelector('input[name="gender"]:checked').value;
console.log("选中值:", selectedValue);
});
</script>
</body>
</html>
通过以上方法可以实现 H5 的单选框功能,包括基础功能、样式自定义和动态交互。
