# 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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。