h5 radiobox实现
h5 radiobox实现
在HTML5中,radiobox通常指的是单选按钮(radio button),用于让用户在一组选项中选择一个。以下是实现radiobox的几种方法:
基本HTML实现
使用<input type="radio">标签创建单选按钮,并通过name属性将多个单选按钮分组:
<input type="radio" id="option1" name="group1" value="1">
<label for="option1">选项1</label>
<input type="radio" id="option2" name="group1" value="2">
<label for="option2">选项2</label>
<input type="radio" id="option3" name="group1" value="3">
<label for="option3">选项3</label>
默认选中
通过checked属性可以设置默认选中的选项:
<input type="radio" id="option1" name="group1" value="1" checked>
<label for="option1">选项1</label>
使用CSS自定义样式
原生单选按钮样式有限,可以通过CSS自定义样式:
<style>
.radio-container {
display: block;
position: relative;
padding-left: 35px;
margin-bottom: 12px;
cursor: pointer;
}
.radio-container input {
position: absolute;
opacity: 0;
}
.checkmark {
position: absolute;
top: 0;
left: 0;
height: 25px;
width: 25px;
background-color: #eee;
border-radius: 50%;
}
.radio-container:hover input ~ .checkmark {
background-color: #ccc;
}
.radio-container input:checked ~ .checkmark {
background-color: #2196F3;
}
.checkmark:after {
content: "";
position: absolute;
display: none;
}
.radio-container input:checked ~ .checkmark:after {
display: block;
}
.radio-container .checkmark:after {
top: 9px;
left: 9px;
width: 8px;
height: 8px;
border-radius: 50%;
background: white;
}
</style>
<label class="radio-container">
<input type="radio" name="radio" checked>
<span class="checkmark"></span>
选项1
</label>
<label class="radio-container">
<input type="radio" name="radio">
<span class="checkmark"></span>
选项2
</label>
使用JavaScript获取选中值
通过JavaScript可以获取用户选择的单选按钮的值:
<input type="radio" id="option1" name="group1" value="1">
<label for="option1">选项1</label>
<input type="radio" id="option2" name="group1" value="2">
<label for="option2">选项2</label>
<button onclick="getSelectedRadio()">获取选中值</button>
<script>
function getSelectedRadio() {
const selected = document.querySelector('input[name="group1"]:checked');
if (selected) {
alert(selected.value);
} else {
alert("未选择任何选项");
}
}
</script>
使用框架实现
在现代前端框架中(如React、Vue等),radiobox的实现更加灵活:
React示例:
import { useState } from "react";
function RadioBox() {
const [selected, setSelected] = useState("1");
return (
<div>
<label>
<input
type="radio"
value="1"
checked={selected === "1"}
onChange={(e) => setSelected(e.target.value)}
/>
选项1
</label>
<label>
<input
type="radio"
value="2"
checked={selected === "2"}
onChange={(e) => setSelected(e.target.value)}
/>
选项2
</label>
</div>
);
}
Vue示例:

<template>
<div>
<label>
<input type="radio" v-model="selected" value="1">
选项1
</label>
<label>
<input type="radio" v-model="selected" value="2">
选项2
</label>
</div>
</template>
<script>
export default {
data() {
return {
selected: "1"
};
}
};
</script>
以上方法涵盖了从原生HTML到现代前端框架的radiobox实现方式,可以根据具体需求选择适合的方案。
