Toggle a simple navigation in Javascript

前端 未结 3 697
时光取名叫无心
时光取名叫无心 2021-01-28 05:24

I want to have a very simple navigation menu. It has to be clickable. So when using this code

相关标签:
3条回答
  • 2021-01-28 05:57

    Why not simplify it to:

    $("#navBtn").click(function() {
      $("#navContent").toggle();
    });
    #navContainer {
      position: relative;
      display: inline-block;
    }
    
    #navContent {
      display: none;
    }
    
    #navContent button {
      display: block;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <body>
    
      <div id="navContainer">
        <button id="navBtn">Menu</button>
        <div id="navContent">
          <button>1</button>
          <button>2</button>
          <button>3</button>
          <button>4</button>
        </div>
      </div>
    
    </body>

    0 讨论(0)
  • 2021-01-28 05:59

    Your code is a rather odd mix of plain JS and jQuery. I'd suggest using one or the other. Here's a simple version of your code using jQuery:

    $(function() {
      $('#navBtn').click(function() {
        $('#navContent').toggle();
      }); 
    });
    #navContainer {
      position: relative;
      display: inline-block;
    }
    
    #navContent button {
      display: block;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div id="navContainer">
      <button id="navBtn">Menu</button>
      <div id="navContent">
        <button>1</button>
        <button>2</button>
        <button>3</button>
        <button>4</button>
      </div>
    </div>

    0 讨论(0)
  • 2021-01-28 06:08

    It would be much easier to make a CSS class that hides the elements, which is then toggled by JS. This answer doesn't require jQuery

    function toggleMenu(){
        document.getElementById('navContent').classList.toggle("hidden")
    }
    #navContainer {
        position: relative;
        display: inline-block;
    }
    
    #navContent button {
        display: block;
    }
    
    .hidden {
        display: none;
    }
    <div id="navContainer">
        <button id="navBtn" onclick="toggleMenu()">Menu</button>
        <div id="navContent" class="hidden">
            <button>1</button>
            <button>2</button>
            <button>3</button>
            <button>4</button>
        </div>
    </div>

    0 讨论(0)
提交回复
热议问题