我想问另一个关于HTML/css/Javascrip的问题.菜单汉堡包按钮工作正常,按下覆盖层即可自动关闭.但关闭按钮不起作用,无论我是否将该按钮的addEventlistener
从click
改为touchstart
,因为它应该只适用于移动设备和平板电脑.我甚至试图将onclick
in svgCancel
放入HTML文件中,并在Java脚本中使用该onclick
的函数,但控制台发送了一个警告,指出该函数尚未定义.我想问一下,现在我的代码中是否有任何错误,或者我应该编写什么来实现此操作?
谢谢!
const menu = document.getElementById('menu');
const svgham = document.getElementById('svgham');
const svgCancel = document.getElementById('svgCancel');
const overlay = document.getElementById('overlay');
menu.addEventListener("click", () => {
overlay.style.display = "flex";
svgham.style.display = "none";
svgCancel.style.display = "flex";
});
svgCancel.addEventListener("click", () => {
overlay.style.display = "none";
svgCancel.style.display = "none";
svgham.style.display = "flex";
});
overlay.addEventListener("click", () => {
overlay.style.display = "none";
svgCancel.style.display = "none";
svgham.style.display = "flex";
});
nav {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: right;
padding: 1rem;
background-color: rgba(46, 46, 46, 0.2);
}
nav a {
display: inline-block;
width: 7rem;
text-align: center;
text-decoration: none;
color: #000000;
}
main {
overflow: scroll;
}
#menu {
margin: 0;
border: 0;
text-align: right;
background-color: transparent;
}
#svgCancel {
display: none;
}
#overlay {
position: fixed;
display: none;
flex-direction: column;
align-items: center;
height: 100vh;
width: 100vw;
top: 3rem;
left: 0;
font-weight: 500;
padding: 4rem 1rem 0;
background-color: rgba(46, 46, 46, 0.1);
backdrop-filter: blur(6px);
}
#overlay a {
font-size: x-large;
margin: 2rem;
}
#overlay a:hover {
padding: 0.5rem 1rem;
border: solid 1px;
}
<nav>
<a id="menu">
<svg id="svgham" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M2 6C2 5.44772 2.44772 5 3 5H21C21.5523 5 22 5.44772 22 6C22 6.55228 21.5523 7 21 7H3C2.44772 7 2 6.55228 2 6Z" fill="currentColor" /><path d="M2 12.0322C2 11.4799 2.44772 11.0322 3 11.0322H21C21.5523 11.0322 22 11.4799 22 12.0322C22 12.5845 21.5523 13.0322 21 13.0322H3C2.44772 13.0322 2 12.5845 2 12.0322Z" fill="currentColor" /><path d="M3 17.0645C2.44772 17.0645 2 17.5122 2 18.0645C2 18.6167 2.44772 19.0645 3 19.0645H21C21.5523 19.0645 22 18.6167 22 18.0645C22 17.5122 21.5523 17.0645 21 17.0645H3Z" fill="currentColor" /></svg>
<svg version="1.1" id="svgCancel" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="18px" height="18px" viewBox="0 0 18 18" style="enable-background:new 0 0 24 24;" xml:space="preserve"><line style="fill:none;stroke:#000000;stroke-width:2.5;stroke-miterlimit:10;" x1="0" y1="0" x2="18" y2="18"/><line style="fill:none;stroke:#000000;stroke-width:2.5;stroke-miterlimit:10;" x1="0" y1="18" x2="18" y2="0"/></svg>
</a>
</nav>
<main>
<div id="overlay">
<a>a</a>
<a>b</a>
<a>c</a>
<a>d</a>
</div>
</main>