各位大大,上一篇雖然有發文過,不好意思,造成你們困擾,目前遇到問題是變成手機和平板尺寸時,我點擊漢堡選單,沒有任何反應,我還是停留打轉。
這是youtube網址:
https://www.youtube.com/watch?v=bk3Y4heVdFs&t=360s
https://www.youtube.com/watch?v=XhGN_Np1obg
這是執行照片:
這是原始程式碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>chatGDT drop menu1</title>
<style>
/* 引入 Google Fonts */
@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
/* 重置樣式 */
* {
padding: 0;
margin: 0;
font-family: 'Poppins', monospace;
box-sizing: border-box;
}
/* 標頭樣式 */
header {
width: 100%;
height: 80px;
background: #2bab0d;
display: flex;
justify-content: flex-start;
align-items: center;
padding: 0 20px;
}
/* 漢堡選單樣式 */
.menu-toggle {
display: none; /*隱藏起來*/
font-size: 20px;
color: #fff;
cursor: pointer;
/* 註解:將漢堡選單置於左上角 */
position: absolute;
top: 10px;
left: 10px;
}
/* 選單樣式 */
nav ul {
list-style: none;
display: flex;
}
nav ul li {
position: relative;
}
nav ul li a {
display: block;
padding: 20px 25px;
color: #fff;
text-decoration: none;
text-align: center;
font-size: 20px;
}
/*子選單部分*/
nav ul li ul.dropdown li {
display: block;
}
nav ul li ul.dropdown {
width: 100%;
background: #2bab0d;
position: absolute;
top: 100%;
left: 0;
z-index: 999;
display: none;
}
nav ul li a:hover {
background: #00ff00;
}
/*子選單往下拉*/
nav ul li:hover ul.dropdown {
display: block;
}
/* 媒體查詢 */
@media (max-width: 767px) {
header {
justify-content: flex-start;
}
.menu-toggle {
display: block;
}
nav ul {
display: none;
flex-direction: column;
align-items: flex-start;
}
nav ul li {
width: 100%;
text-align: left;
}
}
</style>
</head>
<body>
<header>
<div class="menu-toggle">☰</div>
<nav>
<ul class="menu">
<li><a href="#">我的首頁</a>
<ul class="dropdown">
<li><a href="#">鳥類網站簡介</a></li>
<li><a href="#">我的簡介</a></li>
</ul>
</li>
<li><a href="#">本土鳥類</a>
<ul class="dropdown">
<li><a href="#">台灣藍鵲</a></li>
<li><a href="#">酒紅朱雀</a></li>
<li><a href="#">灰喉山椒鳥</a></li>
</ul>
</li>
<li><a href="#">過境候鳥</a>
<ul class="dropdown">
<li><a href="#">銅藍鶲</a></li>
<li><a href="#">銹鵐</a></li>
</ul>
</li>
</ul>
</nav>
</header>
</body>
</html>
我想做的功能是類似RWD的navbar,手機和平板尺寸時點,點擊漢堡選單,就張開往下拉出現選單,再點擊漢堡選單,就收起來,該怎麼寫呢?
純CSS,要加下面這兩個。
<style>
@media (max-width: 767px) {
.menu-toggle:focus + nav ul {
display: block;
}
}
</style>
<body>
<header>
<div class="menu-toggle" tabindex="0">☰</div>
</header>
<body>
不過通常我會用js去做。
在css設定一個.active
。如下
<style>
.active{
display:block;
}
</style>
再用js監控menu的click事件
<script>
let isActivedMenu = false //一開始是關閉的
const menuToggle = document.querySelector('.menu-toggle')
const navUl = document.querySelector('nav ul')
menuToggle.onclick = () => {
if (!isActivedMenu) navUl.classList.add('active')
else navUl.classList.remove('active')
isActivedMenu = !isActivedMenu
}
</script>