如何創建:可折疊的側邊欄
學習如何創建可折疊的側邊欄菜單。
點擊按鈕以打開可折疊側邊欄:
創建可折疊側邊欄
第一步 - 添加 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 導航欄