如何为关联.checked类的.todo-name元素添加删除线CSS样式
解决方案:勾选状态关联文本删除线样式
问题说明
需要实现:当.checkmark元素拥有.checked类时,为同一.checkbox-container容器下的.todo-name元素添加text-decoration: line-through;样式。尝试过部分CSS选择器但未生效,询问是否可通过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> <!-- 这个项没有.checked类,不应添加删除线 --> <label class="checkbox-container" for="1"> <span class="todo-name">Todo</span> <input onclick="updateStatus(this)" type="checkbox" id="1"> <span class="checkmark"></span> </label> <style> /*.todo-name{text-decoration: line-through;}*/ /* 未生效的尝试 */ /* .checkbox-container .checked ~ .todo-name { text-decoration: line-through; } .checkbox-container:not(.checked) .todo-name {text-decoration: line-through;} */ </style>
CSS实现方案
方案1:使用:has()选择器(推荐,现代浏览器支持)
CSS的:has()伪类可以选择包含特定子元素的父容器,直接作用到目标元素,无需调整HTML结构:
.checkbox-container:has(.checkmark.checked) .todo-name { text-decoration: line-through; }
该选择器目前已被Chrome、Firefox(需开启布局.css.has-selector.enabled)、Edge等主流浏览器支持。
方案2:调整HTML结构后使用兄弟选择器
如果需要兼容不支持:has()的旧浏览器,可以调整HTML结构,将.checkmark移到.todo-name之前,然后利用兄弟选择器~:
<label class="checkbox-container" for="0"> <span class="checkmark checked"></span> <span class="todo-name">Todo</span> <input onclick="updateStatus(this)" type="checkbox" id="0" checked=""> </label>
对应的CSS:
.checkmark.checked ~ .todo-name { text-decoration: line-through; }
JS备选方案
如果上述CSS方案无法满足需求,可通过JavaScript实现状态关联:
// 初始化页面已勾选的项 document.querySelectorAll('.checkbox-container .checkmark.checked').forEach(checkmark => { const todoName = checkmark.closest('.checkbox-container').querySelector('.todo-name'); todoName.style.textDecoration = 'line-through'; }); // 监听复选框点击事件,更新样式 document.querySelectorAll('.checkbox-container input[type="checkbox"]').forEach(input => { input.addEventListener('click', function() { const container = this.closest('.checkbox-container'); const todoName = container.querySelector('.todo-name'); const checkmark = container.querySelector('.checkmark'); if (this.checked) { checkmark.classList.add('checked'); todoName.style.textDecoration = 'line-through'; } else { checkmark.classList.remove('checked'); todoName.style.textDecoration = 'none'; } }); });
内容的提问来源于stack exchange,提问作者Lineloop
相关产品推荐
相关产品推荐

