如何创建:可折叠的侧边栏
学习如何创建可折叠的侧边栏菜单。
点击按钮以打开可折叠侧边栏:
创建可折叠侧边栏
第一步 - 添加 HTML:
<div id="mySidebar" class="sidebar"> <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a> <a href="#">About</a> <a href="#">Services</a> <a href="#">Clients</a> <a href="#">Contact</a> </div> <div id="main"> <button class="openbtn" onclick="openNav()">☰ Open Sidebar</button> <h2>Collapsed Sidebar</h2> <p>Content...</p> </div>
第二步 - 添加 CSS:
/* 侧边栏菜单 */
.sidebar {
height: 100%; /* 100% Full-height */
width: 0; /* 0 width - 使用 JavaScript 更改此设置 */
position: fixed; /* 保持在原位置 */
z-index: 1; /* 保持在顶部 */
top: 0;
left: 0;
background-color: #111; /* 黑色 */
overflow-x: hidden; /* 禁用水平滚动 */
padding-top: 60px; /* 将内容置于距顶部 60px 的位置 */
transition: 0.5s; /* 0.5 秒的过渡效果以滑动侧边栏 */
}
/* The sidebar links */
.sidebar a {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 25px;
color: #818181;
display: block;
transition: 0.3s;
}
/* 当您将鼠标悬停在导航链接上时,更改其颜色 */
.sidebar a:hover {
color: #f1f1f1;
}
/* 关闭按钮的位置和样式(右上角) */
.sidebar .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-left: 50px;
}
/* 用于打开侧边栏的按钮 */
.openbtn {
font-size: 20px;
cursor: pointer;
background-color: #111;
color: white;
padding: 10px 15px;
border: none;
}
.openbtn:hover {
background-color: #444;
}
/* 设置页面内容样式 - 如果您想在打开侧边导航时将页面内容向右推动,请使用此样式 */
#main {
transition: margin-left .5s; /* 如果您想要过渡效果 */
padding: 20px;
}
/* 在高度小于 450 像素的小屏幕上,更改侧边栏的样式(减少内边距和字体大小) */
@media screen and (max-height: 450px) {
.sidebar {padding-top: 15px;}
.sidebar a {font-size: 18px;}
}
第三步 - 添加 JavaScript:
/* 将侧边栏的宽度设置为 250px,并将页面内容的左外边距设置为 250px */
function openNav() {
document.getElementById("mySidebar").style.width = "250px";
document.getElementById("main").style.marginLeft = "250px";
}
/* 将侧边栏的宽度设置为 0,并将页面内容的左外边距设置为 0 */
function closeNav() {
document.getElementById("mySidebar").style.width = "0";
document.getElementById("main").style.marginLeft = "0";
}
相关页面
教程:CSS 导航栏