HTML5 <label></label>
元素用於將文本描述與表單控件相關聯,增強可用性和可訪問性。有兩種將標籤與形式控件相關聯的主要方法:
包裝方法:
您可以在<label></label>
元素中包裹表單控件。這是一個例子:
<code class="html"><label> Name: <input type="text" name="username"> </label></code>
在此方法中,文本“名稱:”用作標籤,並且自動與<input>
元素關聯。
for
屬性方法:
您可以在<label></label>
元素中使用for
屬性,並將其設置為表單控件的id
。這是一個例子:
<code class="html"><label for="username">Name:</label> <input type="text" id="username" name="username"></code>
在此方法中,文本“名稱:”與id
“用戶名”的<input>
元素關聯。
這兩種方法都是有效的,並且得到了廣泛的支持,但是當標籤和控件不相鄰或要分別將樣式應用於標籤時, for
屬性方法是首選的。
將<label></label>
元素與表單控件一起提供了幾個好處:
為了通過將標籤與形式的輸入正確關聯來提高可訪問性,請遵循以下最佳實踐:
<label></label>
元素:<label></label>
元素將標籤與每個形式控件相關聯。這對於依靠屏幕閱讀器的用戶至關重要。for
屬性方法,或者您需要單獨樣式。否則,包裝方法就足夠了。title
屬性用作適當的<label></label>
的替代。 title
屬性可能不會由所有屏幕讀取器宣布,如果與<label></label>
文本衝突,可能會引起混亂。是的, <label></label>
元素可以與各種類型的表單控件一起使用。這是可以將其應用於不同類型的方式:
文本輸入:
<code class="html"><label for="email">Email:</label> <input type="email" id="email" name="email"></code>
標籤“電子郵件:”與電子郵件輸入字段關聯。
複選框:
<code class="html"><label> <input type="checkbox" name="subscribe" value="yes"> Subscribe to newsletter </label></code>
文本“訂閱新聞通訊”與復選框關聯。單擊文本將切換複選框。
無線電按鈕:
<code class="html"><label> <input type="radio" name="color" value="red"> Red </label> <label> <input type="radio" name="color" value="blue"> Blue </label></code>
每個標籤都與其各自的廣播按鈕相關聯。單擊“紅色”或“藍色”將選擇“相應的無線電”按鈕。
選擇下拉:
<code class="html"><label for="country">Country:</label> <select id="country" name="country"> <option value="usa">USA</option> <option value="canada">Canada</option> </select></code>
標籤“ country:”與下拉菜單相關聯。
Textarea:
<code class="html"><label for="comments">Comments:</label> <textarea id="comments" name="comments"></textarea></code>
標籤“評論:”與文本股相關聯。
通過正確使用具有不同類型的表單控件的<label></label>
元素,您可以同時增強Web表單的可用性和可訪問性。
以上是我如何使用html5&lt; label&gt; 將標籤與形式控件相關聯的元素?的詳細內容。更多資訊請關注PHP中文網其他相關文章!