导航工作正常,但是当单击链接时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()">×</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()">☰ open</span>
&#13;
单击链接时,sidenav应该关闭
答案 0 :(得分:1)
您的代码完美无缺。您似乎忘记在实际链接上的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()">×</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()">☰ open</span>
答案 1 :(得分:0)
试试这个:
<强> HTML:强>
<div id="mySidenav" class="sidenav jsSideNav">
<a href="javascript:void(0)" class="">×</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" class="jsToggleNav">☰ open</span>
<强> CSS:强>
.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;
}
.sidenav.active {
width: 250px;
}
<强> JS:强>
$(document).ready(function(){
$(".jsToggleNav").on('click', function(){
if($(".jsSideNav").hasClass('active')) {
$(".jsSideNav").removeClass('active');
} else {
$(".jsSideNav").addClass('active');
}
})
});
我假设你正在使用jquery,也遵循专门用于js操作的类名的命名约定。
希望这可以帮到你。