纯CSS无JavaScript实现阅读更多按钮类名图标切换
实现方案
纯CSS不具备动态修改DOM元素类名的能力,但你不需要通过动态加类的方式实现需求,基于你已经在用的checkbox状态切换逻辑,直接控制两个箭头元素的显隐即可,完全适配仅通过类名调用图标的要求,全程不需要JavaScript。
具体修改步骤
- 修正现有HTML里的箭头元素类名:你原本第二个箭头span同时写了向下、向上两个箭头的类,删掉多余的向下箭头类,让两个span分别只对应一个状态的图标类:
<input type="checkbox" id="read_more_checkbox"> <label for="read_more_checkbox" class="read_more_label" read_more="Show more" read_less="Show less"> <span class="ico-arrow ico-angle-down"></span> <span class="ico-arrow ico-angle-up"></span> </label> <div class="read_more_txt">Lorem ipsum dolor sit amet consectetur adipisicing elit. Quibusdam possimus ad necessitatibus quas veritatis. At accusantium enim praesentium nihil porro consequatur aperiam quia fuga adipisci in, incidunt velit fugiat laborum.</div>
- 在原有CSS基础上新增箭头显隐控制规则,利用
:checked伪类匹配不同状态下要显示的箭头:
.read_more_txt { display: none; } #read_more_checkbox { display: none; } #read_more_checkbox:checked~.read_more_txt { display: block; } .read_more_label { text-decoration: underline; font-weight: bold; cursor: pointer; } #read_more_checkbox~.read_more_label:before { content: attr(read_more); margin-right: 4px; } #read_more_checkbox:checked~.read_more_label::before { content: attr(read_less); } /* 箭头显隐控制规则 */ /* 默认未选中(展示更多状态):显示向下箭头,隐藏向上箭头 */ #read_more_checkbox ~ .read_more_label .ico-angle-down { display: inline-block; } #read_more_checkbox ~ .read_more_label .ico-angle-up { display: none; } /* 选中状态(收起状态):显示向上箭头,隐藏向下箭头 */ #read_more_checkbox:checked ~ .read_more_label .ico-angle-down { display: none; } #read_more_checkbox:checked ~ .read_more_label .ico-angle-up { display: inline-block; }
方案说明
- 两个箭头元素提前写入DOM,各自保留图标库要求的固定类名,不需要动态修改类属性,图标可以正常加载
- 状态判断完全依赖原生checkbox的选中态,和你已经实现的内容展开、文案切换逻辑完全兼容,没有额外依赖
- 全程没有使用JavaScript,符合限制要求
内容的提问来源于stack exchange,提问作者Rony Cohen
相关产品推荐
相关产品推荐

