折叠侧边栏
创建于 2024-12-03 /
56
字体:
[默认]
[大]
[更大]
了解如何创建可折叠的侧边栏菜单。
× About Services Clients Contact
点击按钮打开可折叠侧边栏:
亲自试一试 »
创建折叠侧边栏
步骤 1) 添加 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>
步骤 2) 添加 CSS:
实例
/* 侧边栏菜单 */.sidebar {
height: 100%; /* 100% 全高 */
width: 0; /* 0 宽度 - 使用 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 秒过渡效果在侧边栏中滑动 */
}
/* 侧边栏链接 */
.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 像素的小屏幕上,更改 sidenav 的样式(更少的填充和更小的字体大小)*/
@media screen and (max-height: 450px) {
.sidebar {padding-top: 15px;}
.sidebar a {font-size: 18px;}
}
步骤 3) 添加 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 导航栏教程,了解有关导航栏的更多信息。
0 人点赞过