首页 > 解决方案 > 如何切换导航栏可见性?

问题描述

我是 javascript 的初学者。我想使用切换方法添加隐藏和显示按钮。这是我的html。

<body>
  <header>
    <li><a href="#">Mécanique</a>
      <ul class="sub-menu">
        <li><a href="#">Mécanique du point</a></li>
        <li><a href="#">Mécanique du solide</a></li>
      </ul>
    </li>

  </header>
</body>

标签: javascriptjquery

解决方案


在 StackOverflow 上提问之前,先了解一下事情是如何工作的。我们都还在学习,但是,我们必须自己尝试。

除此之外,这里是如何通过单击包含“Mécanique”字样的标签jQuery来隐藏/显示的方法,我会给它一个,以便我们稍后可以参考它。.sub-menuaIDJavaScript

// we put everything in the document.ready handler to ensure that the document has finished loading.
$(document).ready(function() {
  // reference the 'a' tag that I gave it an id of 'trigger', and also referencing the .sub-menu ul.
  var trigger = $('#trigger'),
    menu = $('.sub-menu');
  // adding the event listener to the #trigger to hide/show the .sub-menu ul.
  trigger.on('click', function(e) {
    // cancel the default behaviour when clicking a link.
    e.preventDefault();
    // hide/show the menu.
    menu.toggle();
  });  
});
ul.sub-menu {
  // by default, let's make the .sub-menu ul hidden.
  display: none;
}
    <body>
      <header>
        <li><a href="#" id="trigger">Mécanique</a>
          <ul class="sub-menu">
            <li><a href="#">Mécanique du point</a></li>
            <li><a href="#">Mécanique du solide</a></li>
          </ul>
        </li>

      </header>
      <script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
    </body>

希望我把你推得更远。


推荐阅读