半折叠式侧边栏是一种常见的网页设计元素,当用户点击折叠按钮时,侧边栏会折叠起来,只显示一个小图标或者折叠按钮,点击展开按钮时,侧边栏会再次展开。
下面是一个使用HTML、CSS和JavaScript实现半折叠式侧边栏的示例代码:
HTML代码:
CSS代码(style.css):
.sidebar {
width: 200px;
height: 100vh;
background-color: #333;
padding: 20px;
color: white;
position: fixed;
top: 0;
left: 0;
transition: all 0.3s ease;
}
.sidebar.collapsed {
width: 50px;
}
.sidebar .toggle-btn {
cursor: pointer;
display: flex;
flex-direction: column;
justify-content: space-between;
width: 20px;
height: 20px;
}
.sidebar .toggle-btn span {
width: 100%;
height: 2px;
background-color: white;
}
.sidebar-menu {
list-style: none;
padding-left: 0;
margin-top: 40px;
}
.sidebar-menu li {
margin-bottom: 10px;
}
JavaScript代码(script.js):
const toggleBtn = document.querySelector('.toggle-btn');
const sidebar = document.querySelector('.sidebar');
toggleBtn.addEventListener('click', function() {
sidebar.classList.toggle('collapsed');
});
以上代码中,使用了HTML的基本结构来创建侧边栏容器以及相应的菜单项。CSS样式设置了侧边栏的宽度、背景颜色、内边距等样式,以及折叠状态下的样式。JavaScript代码则是通过监听折叠按钮的点击事件来切换侧边栏的折叠状态。
通过将以上代码保存为相应的文件(例如index.html、style.css和script.js),并在浏览器中打开index.html文件,就可以看到一个具有半折叠式侧边栏效果的页面了。
上一篇:半展开折叠工具栏
下一篇:Ban指令无法正常运行。