Bootstrap 4: How Do I Close a dropdown-menu when a

2019-07-27 12:29发布

问题:

I have a Bootstrap dropdown menu in a navbar. You need to click the menu to open it. If you click outside of the menu, it will close. If you click one of the items (class dropdown-item), it remains open. I would like to close it when a menu item is clicked. All of the items I have found are referencing earlier version of Bootstrap.

Here is my code. The first time I click a menu item when I enter the website, the menu closes. The next time I click a menu item it remains open.

<li class="nav-item dropdown">
  <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    <%= "#{t :link_products}" %>
  </a>
  <div class="dropdown-menu" aria-labelledby="navbarDropdown">
    <div class="dropdown-item"><%= link_to "#{t :link_app}", locale_root_path(anchor: "games"), class: "page-scroll" %></div>
    <div class="dropdown-item"><%= link_to "#{t :link_vr}", locale_root_path(anchor: "vrsection"), class: "page-scroll" %></div>
    <div class="dropdown-item"><%= link_to "#{t :link_tesserart}", locale_root_path(anchor: "tesserartview"), class: "page-scroll" %></div>
    <div class="dropdown-item"><%= link_to "#{t :link_books}", locale_root_path(anchor: "booksview"), class: "page-scroll" %></div>
    <div class="dropdown-divider"></div>
    <div class="dropdown-item"><%= link_to "#{t :link_home}", locale_root_path %></div>
  </div>
</li>

I assume I will need to use Javascript but I'm not sure how to code the solution. I do have jQuery in my Rails application. Here is code that I use for nav pills to display my tab-content when the tab link is clicked.

$(window).load(function() {

  $('#appPills a', '#vrPills a').click(function (e) {
    e.preventDefault()
    $(this).tab('show')
  })

})

I tried both of these but it did not work.

$(window).load(function() {

  $('.dropdown-item a').click(function (e) {
    $(".dropdown-menu").toggleClass("close");
  })

})

$(window).load(function() {

  $('.dropdown-item').click(function (e) {
    $(".dropdown-menu").toggleClass("close");
  })

})

回答1:

try this

    <div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown button
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item" href="#">Action</a>
    <a class="dropdown-item" href="#">Another action</a>
    <a class="dropdown-item" href="#">Something else here</a>
  </div>
</div>


回答2:

I remembered that I also use a SmoothScroll script in the dropdown menu. That script is executed for class page-scroll. I found the JS code for class page-scroll and added the following code before the page scrolling code.

$("#navbarDropdown").dropdown('hide')

The dropdown menu closes when the menu item clicks as expected.