如何創建:帶有下拉菜單的響應式導航欄
- 上一頁 側邊導航欄中的下拉菜單
- 下一頁 子導航菜單
學習如何創建帶有下拉菜單的響應式導航欄。
帶有下拉菜單的響應式頂部導航欄
創建帶有下拉菜單的響應式頂部導航
第一步 - 添加 HTML:
<div class="topnav" id="myTopnav"> <a href="#home" class="active">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> <div class="dropdown"> <button class="dropbtn">Dropdown <i class="fa fa-caret-down"></i> </button> <div class="dropdown-content"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> </div> <a href="#about">About</a> <a href="javascript:void(0);" class="icon" onclick="myFunction()">☰</a> </div>
第二步 - 添加 CSS:
/* 為頂部導航添加黑色背景色 */ .topnav { background-color: #333; overflow: hidden; } /* 設置導航欄中鏈接的樣式 */ .topnav a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } /* 添加一個活動類來突出顯示當前頁面 */ .active { background-color: #04AA6D; color: white; } /* 在小屏幕上隱藏應打開和關閉頂部導航的鏈接 */ .topnav .icon { display: none; } /* 下拉菜單容器 - 用于定位下拉菜單內容 */ .dropdown { float: left; overflow: hidden; } /* 設置下拉菜單按鈕的樣式以使其適應頂部導航欄 */ .dropdown .dropbtn { font-size: 17px; border: none; outline: none; color: white; padding: 14px 16px; background-color: inherit; font-family: inherit; margin: 0; } /* 設置下拉菜單內容的樣式(默認為隱藏) */ .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } /* 設置下拉菜單內的鏈接樣式 */ .dropdown-content a { float: none; color: black; padding: 12px 16px; text-decoration: none; display: block; text-align: left; } /* 在鼠標懸停時,為頂部導航欄鏈接和下拉菜單按鈕添加深色背景 */ .topnav a:hover, .dropdown:hover .dropbtn { background-color: #555; color: white; } /* 在鼠標懸停時,為下拉菜單鏈接添加灰色背景 */ .dropdown-content a:hover { background-color: #ddd; color: black; } /* 當用戶將鼠標移到下拉菜單按鈕上時,顯示下拉菜單 */ .dropdown:hover .dropdown-content { display: block; } /* 當屏幕寬度小于 600 像素時,隱藏除第一個鏈接("Home")之外的所有鏈接。顯示應打開和關閉頂部導航欄(.icon)的鏈接 */ @media screen and (max-width: 600px) { .topnav a:not(:first-child), .dropdown .dropbtn { display: none; } .topnav a.icon { float: right; display: block; } } /* 當用戶點擊圖標時,JavaScript會將 "responsive" 類添加到頂部導航欄。這個類使頂部導航欄在小屏幕上看起來更好(垂直顯示鏈接而不是水平顯示) */ @media screen and (max-width: 600px) { .topnav.responsive {position: relative;} .topnav.responsive a.icon { position: absolute; right: 0; top: 0; } .topnav.responsive a { float: none; display: block; text-align: left; } .topnav.responsive .dropdown {float: none;} .topnav.responsive .dropdown-content {position: relative;} .topnav.responsive .dropdown .dropbtn { display: block; width: 100%; text-align: left; } }
第三步 - 添加 JavaScript:
/* 當用戶點擊圖標時,在頂部導航欄中添加和刪除 "responsive" 類之間進行切換 */ function myFunction() { var x = document.getElementById("myTopnav"); if (x.className === "topnav") { x.className += " responsive"; } else { x.className = "topnav"; } }
相關頁面
教程:CSS 下拉菜單
教程:如何創建可點擊的下拉菜單
教程:CSS 導航欄
教程:如何創建側邊導航欄
- 上一頁 側邊導航欄中的下拉菜單
- 下一頁 子導航菜單