设置复选框时我通常使用以下内容:
<input ....>
<label for="...">Lorem ipsum</label>
我使用样式 label::before 的标准方法来模拟复选框的样式,具体取决于复选框是否已被选中:
input label{....}
input::checked label{....}
但是,Wordpress 插件迫使我使用以下语法:
<label>....
<input....>
</label>
由于 CSS 无法遍历 DOM,我常用的纯 CSS 方法在这里不起作用。
还有其他建议吗?也许是 jQuery?或者我缺少一个纯 CSS 解决方案吗?
AFAIK,你不能用 CSS 来做到这一点,因为它不能遍历 DOM(正如你自己提到的)。
不幸的是
label:checked
也不起作用。
所以您正在寻找 JS/jQuery 解决方案:
$(function() {
$(':checkbox').on('change', function() {
$(this).closest('label').toggleClass('active', $(this).is(':checked') );
});
});
label {
border: 2px solid red;
}
.active {
border-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="checkbox" />
</label>
可能存在标签位于输入之前的情况...那么我建议使用
for
属性,以确保标签与输入相关,那么代码应该是:
$(function() {
$(':checkbox').on('change', function() {
$('label[for='+ $(this).attr('id') + ']' ).toggleClass('active', $(this).is(':checked') );
});
});
label {
border: 2px solid red;
}
.active {
border-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="idforcheckbox">This is the label</label>
<input id="idforcheckbox" type="checkbox" />
是的,你需要使用 JS。 CSS 无法处理父母。看看这个 jQuery 代码:
$(document).on('click','input[type="checkbox"]',function() {
if(!$(this).is(':checked')) {
$(this).parent().removeClass('checked');
} else {
$(this).parent().addClass('checked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="checkbox">
</label>
现在只需使用 CSS 即可完成:
label:has(input:checked) {
/* styles for labels that have a nested checked input */
}
使用上面的选择器来设置“选中”输入的样式。
对于“未选中”的输入样式标签元素
label {
/* styles for labels that have a nested unchecked input */
}
或者,为了更具体
label:not(:has(input:checked)) {
/* styles for labels that have a nested unchecked input */
}