如何創建:畫布外菜單

學習如何創建畫布外菜單。



親自試一試

創建畫布外菜單

第一步 - 添加 HTML:

<div id="mySidenav" class="sidenav">
  <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>
<!-- 使用任意元素打開側邊導航 -->
<span onclick="openNav()">open</span>
<!-- 如果您希望側邊導航將頁面內容推向右側,請將所有頁面內容添加到此 div 內(如果只想讓側邊導航停留在頁面頂部,則無需使用此設置) -->
<div id="main">
  ...
</div>

第二步 - 添加 CSS:

/* 側邊導航菜單 */
.sidenav {
  height: 100%; /* 100% 全高 */
  width: 0; /* 0 width - 通過 JavaScript 更改此設置 */
  position: fixed; /* 保持原位 */
  z-index: 1; /* 保持在頂部 */
  top: 0;
  left: 0;
  background-color: #111; /* 黑色 */
  overflow-x: hidden; /* 禁用水平滾動 */
  padding-top: 60px; /* 內容距離頂部 60 像素 */
  transition: 0.5s; /* 0.5 秒的過渡效果,使側邊導航欄滑入 */
}
/* 導航菜單鏈接 */
.sidenav a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
  transition: 0.3s;
}
/* 當您將鼠標懸停在導航鏈接上時,更改其顏色 */
.sidenav a:hover {
  color: #f1f1f1;
}
/* 關閉按鈕的位置和樣式(右上角) */
.sidenav .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}
/* 設置頁面內容的樣式 - 如果您希望在打開側邊導航時,將頁面內容推向右側,請使用此選項 */
#main {
  transition: margin-left .5s;
  padding: 20px;
}
/* 在屏幕高度小于 450 像素的小屏幕上,更改側邊導航欄的樣式(減少內邊距和字體大小) */
@media screen and (max-height: 450px) {
  .sidenav {padding-top: 15px;}
  .sidenav a {font-size: 18px;}
}

第三步 - 添加 JavaScript:

畫布外菜單

/* 設置側邊導航的寬度為 250px,頁面內容的左外邊距為250px */
function openNav() {
  document.getElementById("mySidenav").style.width = "250px";
  document.getElementById("main").style.marginLeft = "250px";
}
/* 設置側邊導航的寬度為 0,頁面內容的左外邊距為0 */
function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
  document.getElementById("main").style.marginLeft = "0";
}

親自試一試

下面的例子同樣將側邊導航欄滑入,并將頁面內容推向右側。不過,這次我們在 body 元素上添加了一個半透明(40% 不透明度)的黑色背景色,以“突出顯示”側邊導航欄:

帶透明度的畫布外菜單

/* 設置側邊導航的寬度為 250px,頁面內容的左外邊距為 250px,并給 body 添加黑色背景色 */
function openNav() {
  document.getElementById("mySidenav").style.width = "250px";
  document.getElementById("main").style.marginLeft = "250px";
  document.body.style.backgroundColor = "rgba(0,0,0,0.4)";
}
/* 設置側邊導航寬度為 0,頁面內容左邊距為 0,body 背景色為白色 */
function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
  document.getElementById("main").style.marginLeft = "0";
  document.body.style.backgroundColor = "white";
}

親自試一試

相關頁面

教程:CSS 導航欄