2011-12-16 48 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>

相关问题