我正在设置一个表单,是否可以使文本字符串像复选框一样工作,例如在单击时将其突出显示,而没有实际显示该复选框?
编辑:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script>
<script type="text/javascript">
$(function(){
$('.fake-check').on('click',function(){
if($(this).hasClass('checked')){
$(this).removeClass('checked').children('input').val('');
}else{
$(this).addClass('checked').children('input').val($(this).data('val'));
}
});
});
</script>
<link href="test.css" rel="stylesheet" type="text/css" />
<a class="fake-check" data-val="somevalue">Something<input type="text" name="somefield"></a>
最佳答案
是的,给定以下HTML:
<input type="checkbox" id="test" /><label for="test">Click to check</label>
和CSS:
label {
color: #f00;
}
input {
display: none;
}
input[type=checkbox]:checked + label {
color: #0f0;
}
label {
color: #f00;
}
input {
display: none;
}
input[type=checkbox]:checked + label {
color: #0f0;
}
<input type="checkbox" id="test" checked/>
<label for="test">Click to check</label>
JS Fiddle demo。
当然,这取决于实现
:checked
伪类的浏览器。我已经使用属性等于符号指定了
label
元素,该元素遵循input
的选中type="checkbox"
,但是由于只能选择checkbox
或radio
,因此可以安全地省略特异性。您也可以在兼容的浏览器中,将相同的方法与
::after
伪元素及其content
属性一起使用,更改文本以反映复选框的状态。例如,使用以下HTML:<input type="checkbox" id="test" /><label for="test">Click to</label>
和CSS:
label {
color: #f00;
}
input {
display: none;
}
input[type=checkbox]:checked + label {
color: #0f0;
}
input[type=checkbox] + label::after {
content: ' check';
}
input[type=checkbox]:checked + label::after {
content: ' uncheck';
}
label {
color: #f00;
}
input {
display: none;
}
input[type=checkbox]:checked + label {
color: #0f0;
}
input[type=checkbox] + label::after {
content: ' check';
}
input[type=checkbox]:checked + label::after {
content: ' uncheck';
}
<input type="checkbox" id="test" checked/>
<label for="test">Click to</label>
参考文献:
Adjacent-sibling (
+
) combinator。::before
`::after` pseudo-elements。:checked
pseudo-class。关于html - 使文本像复选框一样,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13167356/