当 .checked 类存在时,我需要插入 text-decoration: line-through; 样式到 .todo-name
(我一直不明白是否可以用 css 来实现,但万一我也可以使用 js 作为最后的机会)
<label class="checkbox-container" for="0"><span class="todo-name">Todo</span>
<input onclick="updateStatus(this)" type="checkbox" id="0" checked="">
<span class="checkmark checked"></span>
</label>
<!--This content does not have .checked and should not change-->
<label class="checkbox-container" for="0"><span class="todo-name">Todo</span>
<input onclick="updateStatus(this)" type="checkbox" id="0">
<span class="checkmark"></span>
</label>
<style>
/*.todo-name{text-decoration: line-through;}*/
/*Not working*/
/*
.checkbox-container .checked ~ .todo-name {
text-decoration: line-through;
}
.checkbox-container:not(.checked) .todo-name {text-decoration: line-through;}
*/
</style>
Codepen项目
最终结果应该是这样的
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您遇到了几个问题。正如评论中提到的,如果您不想使用 JavaScript,则应该使用伪类。
:在本例中检查了。接下来,您将使用 CSS 选择器
~,它选择该元素之后而不是之前的同级元素。因此,尝试使用选择器#0:checked ~ .todo-name选择.todo-name将不起作用,因为名称出现在复选框之前。下面是一个工作版本的示例。
input:checked ~ .todo-name { text-decoration: line-through; }