HTML <label> 標簽
定義和用法
<label>
標簽為 input 元素定義標注(標記)。
label 元素不會向用戶呈現任何特殊效果。不過,它為鼠標用戶改進了可用性。如果您在 label 元素內點擊文本,就會觸發此控件。就是說,當用戶選擇該標簽時,瀏覽器就會自動將焦點轉到和標簽相關的表單控件上。
<label>
標簽的 for 屬性 應當與相關元素的 id 屬性相同。
<label>
標簽可為多個元素定義標簽(標記):
- <input type="checkbox">
- <input type="color">
- <input type="date">
- <input type="datetime-local">
- <input type="email">
- <input type="file">
- <input type="month">
- <input type="number">
- <input type="password">
- <input type="radio">
- <input type="range">
- <input type="search">
- <input type="tel">
- <input type="text">
- <input type="time">
- <input type="url">
- <input type="week">
- <meter>
- <progress>
- <select>
- <textarea>
使用上述元素與 label 的正確方式將有益于以下用戶:
- 屏幕閱讀器用戶(當用戶聚焦在元素上時,將朗讀標簽)
- 難以點擊非常小的區域(例如復選框)的用戶 - 因為當用戶單擊
<label>
元素中的文本時,它會切換輸入(這增加了點擊區域)
另請參閱:
HTML DOM 參考手冊:Label 對象
實例
三個帶有 label 的單選按鈕:
<form action="/action_page.php"> <input type="radio" id="html" name="fav_language" value="HTML"> <label for="html">HTML</label><br> <input type="radio" id="css" name="fav_language" value="CSS"> <label for="css">CSS</label><br> <input type="radio" id="javascript" name="fav_language" value="JavaScript"> <label for="javascript">JavaScript</label><br><br> <input type="submit" value="提交"> </form>
提示和注釋
提示:<label>
的 for 屬性必須等于相關元素的 id 屬性才能將它們綁定在一起。也可以通過將元素放置在 <label>
元素內將標簽綁定到元素。
全局屬性
<label>
標簽還支持 HTML 中的全局屬性。
事件屬性
<label>
標簽還支持 HTML 中的事件屬性。
瀏覽器支持
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome | Edge | Firefox | Safari | Opera |
支持 | 支持 | 支持 | 支持 | 支持 |