如何创建:折叠侧面板

学习如何创建可折叠的侧面板菜单。

亲自试一试

创建折叠的侧面板

第一步 - 添加 HTML:

<div id="mySidepanel" class="sidepanel">
  <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>

<button class="openbtn" onclick="openNav()">☰ Toggle Sidepanel</button>
<h2>Collapsed Sidepanel</h2>
<p>Content...</p>

第二步 - 添加 CSS:

/* 侧面板菜单 */
.sidepanel {
  height: 250px; /* Specify a height */
  width: 0; /* 0 width - change this with JavaScript */
  position: fixed; /* Stay in place */
  z-index: 1; /* Stay on top */
  top: 0;
  left: 0;
  background-color: #111; /* Black*/
  overflow-x: hidden; /* 禁用水平滚动 */
  padding-top: 60px; /* 将内容置于距顶部 60px 的位置 */
  transition: 0.5s; /* 侧面板滑动的 0.5 秒过渡效果 */
}

/* 侧面板链接 */
.sidepanel a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
  transition: 0.3s;
}

/* 当您将鼠标悬停在导航链接上时,更改其颜色 */
.sidepanel a:hover {
  color: #f1f1f1;
}

/* 关闭按钮的位置和样式(右上角) */
.sidepanel .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;
}

第三步 - 添加 JavaScript:

/* 将侧边栏的宽度设置为 250px(显示它) */
function openNav() {
  document.getElementById("mySidepanel").style.width = "250px";
}

/* 将侧边栏的宽度设置为 0(隐藏它) */
function closeNav() {
  document.getElementById("mySidepanel").style.width = "0";
}

亲自试一试

相关页面

教程:CSS 导航栏