2011-12-16 23 views
54

我知道有時好標籤有一個複選框關聯:可能將標籤與複選框關聯而不使用「for = id」?

<input id="something" type="checkbox" value="somevalue" /> 
<label for="something">this is label text</label> 

..但我使用一個ID給它關聯?
我甚至在乎的主要原因是因爲我喜歡能夠點擊標籤來切換複選框的值,但不喜歡使用id這麼簡單的想法。

我想我可以使用jQuery切換點擊標籤的前一個元素(複選框),但也許有一些簡單的我失蹤了。 https://stackoverflow.com/a/2720771/923817看起來像一個解決方案,但用戶說它在IE中不起作用。

回答

129

是的,將輸入放置在標籤內。

<label><input type=checkbox name=chkbx1> Label here</label> 

implicit label association在HTML規範。

+3

+ 1最佳解決方案 - 請參閱[隱式標籤關聯]的HTML規範(http://www.w3.org/TR/html4/interact/forms.html#h -17.9.1)。 – SliverNinja 2011-12-16 17:10:50

+3

在IE中是否可以工作? http://stackoverflow.com/a/2720771/923817表明它不會 – 2011-12-16 17:11:01

2
<label for="something">this is label text</label> 
<input id="something" type="checkbox" value="somevalue" /> 

實際上是對屬性用於屏幕閱讀器的殘疾人,所以沒有用的可訪問性,而無需編寫屬性

3

演示:JsFiddle

.c-custom-checkbox { 
 
    padding-left: 20px; 
 
    position: relative; 
 
    cursor: pointer; 
 
} 
 
.c-custom-checkbox input[type=checkbox] { 
 
    position: absolute; 
 
    opacity: 0; 
 
    overflow: hidden; 
 
    clip: rect(0 0 0 0); 
 
    height: 15px; 
 
    width: 15px; 
 
    padding: 0; 
 
    border: 0; 
 
    left: 0; 
 
} 
 
.c-custom-checkbox .c-custom-checkbox__img { 
 
    display: inline; 
 
    position: absolute; 
 
    left: 0; 
 
    width: 15px; 
 
    height: 15px; 
 
    background-image: none; 
 
    background-color: #fff; 
 
    color: #000; 
 
    border: 1px solid #333; 
 
    border-radius: 3px; 
 
    cursor: pointer; 
 
} 
 
.c-custom-checkbox input[type=checkbox]:checked + .c-custom-checkbox__img { 
 
    background-position: 0 0; 
 
    background-color: tomato; 
 
}
<label class="c-custom-checkbox"> 
 
    <input type="checkbox" id="valueCheck" /> 
 
    <i class="c-custom-checkbox__img"></i>Some Label 
 
</label>