gpt4 book ai didi

javascript - 如何在点击 href 时关闭 sidenav

转载 作者:行者123 更新时间:2023-11-28 15:09:06 24 4
gpt4 key购买 nike

导航工作正常,但点击链接时 sidenav 应该关闭。因为它是一页。我怎样才能做到这一点?有人能帮助我吗。

代码:

function openNav() {
document.getElementById("mySidenav").style.width = "250px";
}

function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}
.sidenav {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
right: 0;
background-color: #111;
overflow-x: hidden;
transition: 0.5s;
padding-top: 60px;
}
<div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
<a id="nav" href="#about">About</a>
<a id="nav" href="#service">Services</a>
<a id="nav" href="#contact">contact</a>

</div>
<p>Click to open</p>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; open</span>

sidenav 应该在点击链接时关闭

最佳答案

您的代码完美运行。您似乎只是忘记了将 closenav() 添加到实际链接上的 onlick 事件。

function openNav() {
document.getElementById("mySidenav").style.width = "250px";
}

function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}
.sidenav {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
right: 0;
background-color: #111;
overflow-x: hidden;
transition: 0.5s;
padding-top: 60px;
}
<div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
<a id="nav" href="#about" onclick="closeNav()">About</a>
<a id="nav" href="#service" onclick="closeNav()">Services</a>
<a id="nav" href="#contact" onclick="closeNav()">contact</a>

</div>
<p>Click to open</p>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; open</span>

关于javascript - 如何在点击 href 时关闭 sidenav,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48807112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com