如何仅使用CSS实现自定义选择框激活时的箭头旋转效果
问题原因
- 你当前CSS中写的
.custom_select_box_1_index:active是鼠标按下时才触发的临时伪类,和你手动给元素添加的.active类不是同一个规则,所以加类名后不生效。 - 你定义的
.default_option_category_index:before伪元素没有设置display: inline-block,CSS transform属性对默认行内元素不生效;同时你伪元素的content为空、未设置宽高,元素本身不可见,实际显示的箭头是HTML里的font-awesome<i>标签,你给伪元素加旋转当然不会影响实际显示的箭头。 - 原生
:active伪类只有按住鼠标的瞬间生效,松开就会恢复,无法保持下拉展开状态,不符合下拉选择框的交互需求。
纯CSS无JS解决方案(推荐用:focus-within方案,兼容性好,无需修改HTML核心结构)
第一步:给外层容器加tabindex属性,让它可以获得焦点
修改你的HTML外层div:
<div class="custom_select_box_1_index" tabindex="1">
第二步:修改CSS规则,替换:active为:focus-within,同时调整箭头控制逻辑
你可以直接控制现有font-awesome箭头的旋转,不需要额外用伪元素生成箭头,修改后的CSS如下:
.custom_select_box_1_index{ font-family: Helvetica; font-size: 19px; color: var(--second-black); box-sizing: content-box; width: 250px; height: 50px; /* 去掉默认焦点外边框 */ outline: none; } .custom_select_box_1_index > ul li{ list-style: none; } /* 控制现有箭头的默认状态 */ #ArrowCategoryIndex{ transform: rotate(180deg); transition: transform 0.2s ease; float: right; margin-right: 15px; line-height: 50px; } .custom_select_box_1_index .select_option_category_index{ background-color: var(--white); border-radius: 10px; box-shadow: 0px 0px 10px 0px rgba(0,0,0,0.05); z-index: 1; display: none; } .select_option_category_index li{ position: relative; margin-left: -38px; background-color: var(--white); border-radius: 10px; width: 230px; padding: 3px 8px; cursor: pointer; } .custom_select_box_1_index .select_option_category_index li:hover{ background: var(--grey); } .category_text{ position: relative; left: 30px; } .custom_select_box_1_index .option{ display: flex; align-items: center; } .icon{ display: flex; align-items: center; margin-left: 15px; } #icon{ color: var(--black); } /* 焦点状态下展开下拉、旋转箭头 */ .custom_select_box_1_index:focus-within .select_option_category_index{ display: block; } .custom_select_box_1_index:focus-within #ArrowCategoryIndex{ transform: rotate(0deg); } /* 如果你还是需要手动加.active类生效,加上下面的规则 */ .custom_select_box_1_index.active .select_option_category_index{ display: block; } .custom_select_box_1_index.active #ArrowCategoryIndex{ transform: rotate(0deg); }
效果说明
点击选择框时外层容器获得焦点,:focus-within规则生效,下拉菜单展开、箭头自动旋转到0度,点击页面其他位置失去焦点自动收起,全程不需要JS代码。
内容的提问来源于stack exchange,提问作者MvTaku Xx
相关产品推荐
相关产品推荐

