菜单最初是在页面加载时打开的,应关闭直到单击

时间:2018-10-18 13:41:38

标签: javascript jquery html css

这可能是一个愚蠢的问题,但是我无法弄清楚为什么在加载页面时显示菜单。我想关闭它,然后在单击它时将其打开,但这是相反的方式,我似乎无法修复它。

<html>
<head>
<script>
    $(document).ready(function () {
    $('#nav p')
        .css({ cursor: "pointer" })
        .on('click', function () {
            var txt = $(this).text() == "MENU" ? "CLOSE" : "MENU";
            $(this).text(txt);
            $(this).next('ul').toggle();
        })
    });
</script>
</head>

<body>
    <div class="left" id="nav">
        <p>CLOSE</p>
        <ul>
            <li id="light">
                <a href="lighting_video.html">Lighting + Video</a>
            </li>
            <li id="photo">
                <a class="active" href="photograms.html">Photograms</a>
            </li>
            <li id="about">
                <a href="about.html">About</a>
            </li>
        </ul>
    </div>
</body>

</html>

2 个答案:

答案 0 :(得分:1)

$(document).ready(function(){
  $('#nav p')
    .css({cursor: "pointer"})
    .on('click', function(){
      var txt =  $(this).text() === "MENU"?"CLOSE":"MENU"; // 3 egals verification
      $(this).text(txt);
      $(this).next('ul').toggle();
  })
  });
ul{
  display: none; /* ADD this */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="left" id="nav">
  <p>CLOSE</p>
  <ul>
<li id="light">
<a href="lighting_video.html">Lighting + Video</a>
</li>
<li id="photo">
<a class="active"href="photograms.html">Photograms</a>
</li>
<li id="about">
<a href="about.html">About</a>
</li></ul>
</div>
</body>
</html>

答案 1 :(得分:0)

您可以通过CSS完成大多数工作。创建.closed类,并将其分配给#nav

#nav.closed > ul{
  display: none;
}

就是这样。 jQuery单击事件中的微小更改就完成了!

请参见下面的代码段。

$(document).ready(function(){
  $('#nav p').on('click', function(){
      $(this).parent().toggleClass("closed");
    });
  });
#nav{
  cursor: pointer;
}
#nav.closed p::after{
  content : "CLOSE";
}
#nav p::after {
  content: "MENU";
}
#nav.closed > ul{
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="left closed" id="nav">
  <p></p>
  <ul>
    <li id="light">
      <a href="lighting_video.html">Lighting + Video</a>
    </li>
    <li id="photo">
      <a class="active"href="photograms.html">Photograms</a>
    </li>
    <li id="about">
      <a href="about.html">About</a>
    </li>
  </ul>
</div>
</body>
</html>