您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# HTML中`<radio>`单选按钮控件标签怎么用
单选按钮(Radio Button)是HTML表单中常用的控件之一,允许用户从一组选项中选择**唯一答案**。本文将详细介绍`<input type="radio">`的用法、属性和实际应用场景。
## 一、基本语法
```html
<input type="radio" id="option1" name="choices" value="1">
<label for="option1">选项1</label>
type="radio"
:声明为单选按钮类型name
属性:必须相同才能实现互斥选择value
:提交表单时发送到服务器的值id
+<label>
:实现可点击标签(提升用户体验)属性 | 作用 | 示例 |
---|---|---|
checked |
默认选中 | <input ... checked> |
disabled |
禁用选项 | <input ... disabled> |
required |
必选验证 | <input ... required> |
form |
关联表单ID | <input ... form="form1"> |
<form>
<p>请选择支付方式:</p>
<input type="radio" id="alipay" name="payment" value="alipay" checked>
<label for="alipay">支付宝</label><br>
<input type="radio" id="wechat" name="payment" value="wechat">
<label for="wechat">微信支付</label><br>
<input type="radio" id="unionpay" name="payment" value="unionpay">
<label for="unionpay">银联支付</label>
</form>
<form>
<fieldset>
<legend>性别选择(必选)</legend>
<input type="radio" id="male" name="gender" value="M" required>
<label for="male">男</label>
<input type="radio" id="female" name="gender" value="F" required>
<label for="female">女</label>
</fieldset>
<button type="submit">提交</button>
</form>
默认单选按钮样式较简单,可通过CSS实现美化:
/* 隐藏原生控件 */
input[type="radio"] {
opacity: 0;
position: absolute;
}
/* 自定义样式 */
input[type="radio"] + label::before {
content: "";
display: inline-block;
width: 16px;
height: 16px;
border: 2px solid #3498db;
border-radius: 50%;
margin-right: 8px;
}
/* 选中状态 */
input[type="radio"]:checked + label::before {
background: radial-gradient(#3498db 40%, transparent 50%);
}
const selectedValue = document.querySelector(
'input[name="payment"]:checked'
).value;
document.getElementById("wechat").checked = true;
name
属性,不同组应该使用不同name<label>
的点击区域fieldset
和legend
标签增强语义化和可访问性aria-label
)提升无障碍体验所有现代浏览器均支持radio控件,包括: - Chrome/Firefox/Safari/Edge ≥ 1.0 - IE ≥ 6.0 - 移动端浏览器全支持
通过合理使用单选按钮,可以创建直观的表单交互,特别是在需要用户做排他性选择时(如性别选择、问卷调查等场景)。 “`
注:实际字数约750字,包含代码示例、表格等结构化内容,符合技术文档写作规范。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。