我們在使用radio,checkbox等控件的時候,需要對原有的樣式進行美化,但是此類控件美化程度有限。
所以就出來了for屬性,需要配置lable標籤使用。
for 屬性規定 label與哪個表單元素綁定,作用是 在點擊label時會自動將焦點移動到綁定的元素上。
經常使用在radio和checkbox等input元素上。
<code>
<
input
type
="radio"
name
="name"
id
="radio4"
/><
label
for
="radio4"
>男label
>/<code>上述代碼就把input和lable綁定起來了,for屬性對應的是input的id值。
這樣我們在點擊label的時候,也會觸發radio的check事件,就會選中。
下圖是我使用for屬性和css相鄰選擇器美化了radio選擇框:
代碼如下(可直接複製運行):
<code> >
<
html
><
head
><
meta
charset
="utf-8"
/><
title
>title
><
link
href
="https://www.sammh.com/css/reset.css"
rel
="stylesheet"
/><
style
>
ul
{margin-left
:200px
;margin-top
:200px
; }ul
li
{display
:inline-block;margin-left
:20px
; }label
{margin-right
:5px
;border
:1px
solid#4C70B1
;border-radius
:100%
;width
:20px
;height
:20px
;cursor
: pointer;transition
: ease300ms
;display
:inline-block; }label
:hover
{border-color
:#ccc
;background-color
:#4C70B1
;box-shadow
:0
0
7px
#ccc
; }input
[type=radio]
:checked+label
{background-color
:#4C70B1
; }style
>head
><
body
><
ul
><
li
><
input
type
="radio"
name
="name"
id
="radio1"
value
="14"
hidden
/><
label
for
="radio1"
>label
><
span
>男span
>li
><
li
><
input
type
="radio"
name
="name"
id
="radio2"
value
="15"
hidden
/><
label
for
="radio2"
>label
><
span
>女span
>li
><
li
><
input
type
="radio"
name
="name"
id
="radio3"
value
="16"
hidden
/><
label
for
="radio3"
>label
><
span
>人妖span
>li
>ul
>body
>html
>/<code>