1

导航工作正常,但单击链接时应关闭 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 应关闭

4

2 回答 2

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()">&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>

于 2018-02-15T14:18:52.797 回答
0

试试这个:

HTML:

<div id="mySidenav" class="sidenav jsSideNav">
          <a href="javascript:void(0)" class="">&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" class="jsToggleNav">&#9776; 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 操作的类名的命名约定。

希望这可以帮到你。

于 2018-03-15T07:00:43.147 回答