我有一个表格,如果单元格被禁用,我希望每个单元格都有红色背景,如果启用,则背景为蓝色。因此,我在每个单元格中插入了一个不可见的复选框。当我有标签而不是表格时,它工作得很好(参见这里的example ),但它不能与表格一起工作。
HTML:
<table id="hours">
<tbody>
<tr>
<td id="tdh00"><input type="checkbox" id="h00"></td>
<td id="tdh01"><input type="checkbox" id="h01"></td>
</tr>
</tbody>
</table>CSS:
input[type=checkbox] { visibility: hidden; }
#hours input[type=checkbox]:checked + #tdh00 { background-color: #265BFA; }
#hours input[type=checkbox]:not(:checked) + #tdh00 { background-color: #FA2421; }发布于 2013-04-16 18:38:11
使用现有的标记,这是行不通的。您正在使用+ (同级)选择器,但表单元格不是复选框的同级。在您给出的示例中,标记为:
<div class="slideOne">
<input type="checkbox" value="None" id="slideOne" name="check" />
<label for="slideOne"></label>
</div>你的是:
<td id="tdh00"><input type="checkbox" id="h00"></td>因此,您正在尝试根据其子元素之一的状态设置父元素的样式,目前仅使用CSS是不可能的。
编辑
查看this working example。该小提琴将label添加回来(这将有助于提高可访问性),并以这样一种方式定位它,使其在视觉上实现您想要的功能。标记需要是:
<table id="hours">
<tbody>
<tr>
<td id="tdh00">
<div>
<input type="checkbox" id="h00">
<label for="h00">Label</label>
</div>
</td>
<td id="tdh01">
<div>
<input type="checkbox" id="h01">
<label for="h01">Label</label>
</div>
</td>
</tr>
</tbody>
</table>和CSS:
table {
width: 450px;
margin: 0 auto;
}
td {
border: 1px solid #333;
padding: 0;
}
td > div { position: relative; }
input[type=checkbox] { visibility: hidden; }
label {
display: block;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: red;
text-indent: -999em;
}
input[type=checkbox]:checked + label { background-color: #265BFA; }每个表单元格中的额外div是必需的,因为Firefox不能处理相对于td元素的定位。
浏览器支持很好,但因为我们使用的是:checked伪类,所以只支持IE9+。使用基于JavaScript的解决方案可以获得更好的支持,但我认为这是渐进式增强的一个很好的候选方案。
编辑2个
如果需要支持旧的IE,那么你需要求助于JavaScript。使用jQuery的Here's an example。
JavaScript只是在表单元格中添加了一类active:大部分工作仍然是使用CSS完成的。
$("#hours input").on('change', function(){
var checkbox = $(this),
tableCell = checkbox.parents('td');
checkbox.is(':checked') ?
tableCell.removeClass('active') :
tableCell.addClass('active');
}).change();超文本标记语言保持不变,而CSS只是略有不同,它们替换了:checked伪类:
td { background-color: #265BFA; }
.active { background-color: red; }发布于 2013-04-16 19:05:17
尝试如下所示:这是JQuery的解决方案:
小提琴: http://jsfiddle.net/RYh7U/138/
HTML :
<table id="hours" border="1">
<tbody>
<tr><td id="tdh00"><input type="checkbox" id="h00"></td><td id="tdh01"><input type="checkbox" id="h01"></td></tr>
</tbody>
</table>
</body>CSS :
input[type=checkbox] { visibility: hidden; }JQuery :
$("#hours td").each(function(e){
var ele = $(this).children('input[type=checkbox]');
var flag = ele.prop('checked');
if(flag)
{
ele.prop('checked', false);
$(this).css("background", "#265BFA");
}
else
{
ele.prop('checked', true);
$(this).css("background", "#FA2421");
}
});
$("#hours td").click(function(e){
var ele = $(this).children('input[type=checkbox]');
var flag = ele.prop('checked');
if(flag)
{
ele.prop('checked', false);
$(this).css("background", "#265BFA");
}
else
{
ele.prop('checked', true);
$(this).css("background", "#FA2421");
}
});https://stackoverflow.com/questions/16034416
复制相似问题