如何实现列表项li处于active激活状态时的目标设计效果?
li激活态样式实现方案

实现思路
- 为激活状态的li添加专属类名(如
.active),通过类选择器定义激活态样式 - 用CSS伪元素
::before实现左侧高亮指示条,无需额外新增DOM节点 - 自定义调整激活态下的背景色、文字色、内边距,匹配设计需求
基础代码示例
HTML结构
<ul class="menu-list"> <li class="menu-item active">首页</li> <li class="menu-item">产品中心</li> <li class="menu-item">关于我们</li> <li class="menu-item">联系我们</li> </ul>
CSS样式
/* 列表基础样式 */ .menu-list { list-style: none; padding: 0; width: 200px; background: #ffffff; } /* li默认样式 */ .menu-item { position: relative; padding: 12px 16px; color: #333333; cursor: pointer; transition: all 0.2s ease; } /* li激活态样式 */ .menu-item.active { background-color: #e6f7ff; color: #1890ff; padding-left: 20px; } /* 左侧高亮指示条 */ .menu-item.active::before { content: ''; position: absolute; left: 0; top: 0; bottom: 0; width: 4px; background-color: #1890ff; } /* 可选hover态,和激活态做区分 */ .menu-item:hover:not(.active) { background-color: #f5f5f5; }
点击切换激活态JS逻辑
const menuItems = document.querySelectorAll('.menu-item') menuItems.forEach(item => { item.addEventListener('click', () => { // 移除所有列表项的激活类 menuItems.forEach(el => el.classList.remove('active')) // 为当前点击项添加激活类 item.classList.add('active') }) })
前端框架中使用说明
- Vue:通过动态class绑定实现,示例:
<li class="menu-item" :class="{active: currentTab === item.id}" v-for="item in tabList" :key="item.id" > {{ item.name }} </li> - React:通过className判断实现,示例:
{tabList.map(item => ( <li key={item.id} className={`menu-item ${currentTab === item.id ? 'active' : ''}`} > {item.name} </li> ))}
内容的提问来源于stack exchange,提问作者RoadToBeacomADev
相关产品推荐
相关产品推荐

