HTML侧边导航栏被覆盖无法点击及hover、选中样式问题求助
解决方案
问题1:菜单项hover效果失效修复
失效核心原因是.menu的z-index设为-1,绝对定位的.container默认层级高于负层级元素,导致导航交互区域被容器遮挡。调整层级即可解决,且不破坏左侧圆角效果:
修改代码:
/* 原.menu的z-index从-1改为0 */ .menu { position: fixed; height: 100vh; width: 150px; background-color: #3D5021; z-index: 0; /* 修改处 */ } /* 给nav加层级,让导航交互元素在容器上层 */ nav { position: relative; z-index: 2; /* 新增 */ height: 100vh; margin-top: 50px; } /* 给container加层级,保证圆角在menu上层,同时低于nav */ .container { position: absolute; z-index: 1; /* 新增 */ width: calc(100vw - 100px); right: 0px; border-top-left-radius: 50px; border-bottom-left-radius: 50px; background-color: #E1E1E1; min-height: 100vh; }
调整后导航交互区域层级高于容器,hover效果会正常触发,容器的左侧圆角依然覆盖在菜单栏上方,不会破坏视觉效果。
问题2:选中态白色选择框+图标变色实现
利用CSS的:checked伪类和兄弟选择器实现联动效果,步骤如下:
第一步:调整HTML结构
把.selector元素移到ul的最后位置,方便选择器联动:
<ul class="nav-links"> <li> <label for="btnDashboard" class="menuButtonIcon selected"><i class="fas fa-tachometer-alt"></i></label> <input type="checkbox" id="btnDashboard" checked> </li> <li> <label for="btnList" class="menuButtonIcon"><i class="fas fa-list-ul"></i></label> <input type="checkbox" id="btnList"> </li> <li> <label for="btnHeatMap" class="menuButtonIcon"><i class="fas fa-map"></i></label> <input type="checkbox" id="btnHeatMap"> </li> <!-- 把selector移到最后 --> <div class="selector"></div> </ul>
第二步:新增CSS样式
/* 给ul加相对定位,作为selector的定位基准 */ .nav-links { position: relative; } /* 选择框基础样式 */ .selector { position: absolute; width: 60px; height: 60px; background-color: #fff; border-radius: 12px; left: 50%; transform: translateX(-50%); transition: top 0.3s ease; /* 加过渡实现平滑位移 */ z-index: -1; /* 放在图标下方 */ } /* 选中时图标变橙色 */ input:checked + .menuButtonIcon i { color: #ff8c00; /* 可自行调整橙色色值 */ } /* 不同选项选中时控制选择框位移 */ #btnDashboard:checked ~ .selector { top: 0; } #btnList:checked ~ .selector { top: 70px; /* 每个li高度60px + 上下margin5px*2 = 70px偏移 */ } #btnHeatMap:checked ~ .selector { top: 140px; }
额外优化
你当前用的是checkbox,可以同时选中多个,建议改成radio单选框,name属性设为同一个值,保证同一时间只有一个选项被选中:
<!-- 把input的type从checkbox改成radio,name统一为menuTab --> <input type="radio" name="menuTab" id="btnDashboard" checked> <input type="radio" name="menuTab" id="btnList"> <input type="radio" name="menuTab" id="btnHeatMap">
内容的提问来源于stack exchange,提问作者A. Vreeswijk
相关产品推荐
相关产品推荐

