Open wingmeng opened 5 years ago
> 在线 DEMO <
思路:
:checked
max-height
opacity
transition
display: none
visibility: hidden
visibility
max-height: 0; opacity: 0
<main class="container"> <nav class="navbar"> <div class="navbar-group"> <input class="navbar-group-switch" id="switch1" type="checkbox" checked> <label class="navbar-group-title" for="switch1">布局</label> <ul class="navbar-group-list"> <li> <a href="#" class="navbar-link">Flex布局</a> </li> <li> <a href="#" class="navbar-link is-active">Grid布局</a> </li> <li> <a href="#" class="navbar-link">Shapes布局</a> </li> <li> <a href="#" class="navbar-link">Columns布局</a> </li> </ul> </div> <div class="navbar-group"> <input class="navbar-group-switch" id="switch2" type="checkbox" checked> <label class="navbar-group-title" for="switch2">组件</label> <ul class="navbar-group-list"> <li> <a href="#" class="navbar-link">按钮</a> </li> <li> <a href="#" class="navbar-link">输入框</a> </li> <li> <a href="#" class="navbar-link">下拉列表</a> </li> <li> <a href="#" class="navbar-link">单复选框</a> </li> </ul> </div> </nav> </main>
body { margin: 0; font-size: 14px; line-height: 1.42858; } .container { max-width: 1170px; padding: 0 15px; margin: 0 auto; } /* 导航容器 */ .navbar { width: 160px; height: 100vh; overflow: auto; color: #353535; box-shadow: inset 1px 0 0 #e0e0e0, inset -1px 0 0 #e0e0e0; } /* 导航分组标题(点击折叠/展开子导航) */ .navbar-group-title { display: flex; justify-content: space-between; align-items: center; padding: 10px; font-weight: 700; cursor: pointer; } .navbar-group-title::after { content: ""; width: 6px; height: 6px; transform: rotate(225deg); border-style: solid; border-width: 2px 0 0 2px; transition: transform .3s; } /* 子导航列表 */ .navbar-group-list { max-height: 0; /* 用以实现过渡动画 */ padding: 0; margin: 0; visibility: hidden; /* 元素不可见,避免被 tab-index 索引 */ opacity: 0; /* 用以实现过渡动画 */ overflow: hidden; transition: all ease-in-out .3s; list-style: none; } /* 导航链接 */ .navbar-link { display: block; padding: 0 calc(10px + 1.5em); line-height: 40px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-decoration: none; color: inherit; } .navbar-link:hover, .navbar-link.is-active { color: #36b3ee; background: rgb(54, 179, 238, .1); } /* 控制子导航展开/折叠的复选框 */ .navbar-group-switch { /* 剪切式隐藏,保留键盘可访问性 */ position: absolute; clip: rect(0, 0, 0, 0); } .navbar-group-switch:focus + .navbar-group-title { background: rgb(54, 179, 238, .1); } .navbar-group-switch:checked + .navbar-group-title::after { transform: rotate(45deg); } .navbar-group-switch:checked ~ .navbar-group-list { max-height: 500px; /* 根据实际情况合理设置其值 */ visibility: visible; opacity: 1; }
题目:
我的回答:
> 在线 DEMO <
思路:
:checked
伪类,配合 +(临近选择器) 和 ~(兄弟选择器),来实现子导航展开/折叠的交互效果;max-height
和opacity
,配合transition
实现过渡动画效果;max-height
应根据实际情况设置合适的值,太大会造成“卡顿”现象,太小会剪裁掉内容;display: none
或visibility: hidden
的方式隐藏 checkbox;visibility
来控制元素的可见性,避免元素视觉不可见时(max-height: 0; opacity: 0
),被 Tab 键索引。