How to implement a Navbar Dropdown Hover in Bootstrap v4?

前端 未结 20 1000
猫巷女王i
猫巷女王i 2020-12-02 05:40

I am a bit confused on the new bootstrap version since they changed dropdown menus to divs:

20条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 06:17

    (June 2020) I found this solution and I thought I should post it here:

    Bootstrap version: 4.3.1

    The CSS part:

    .navbar .nav-item:not(:last-child) {
      margin-right: 35px;
    }
    
    .dropdown-toggle::after {
       transition: transform 0.15s linear;
    }
    
    .show.dropdown .dropdown-toggle::after {
      transform: translateY(3px);
    }
    
    .dropdown-menu {
      margin-top: 0;
    }
    

    The jQuery part:

    const $dropdown = $(".dropdown");
    const $dropdownToggle = $(".dropdown-toggle");
    const $dropdownMenu = $(".dropdown-menu");
    const showClass = "show";
    
    $(window).on("load resize", function() {
      if (this.matchMedia("(min-width: 768px)").matches) {
        $dropdown.hover(
          function() {
            const $this = $(this);
            $this.addClass(showClass);
            $this.find($dropdownToggle).attr("aria-expanded", "true");
            $this.children($dropdownMenu).addClass(showClass);
          },
          function() {
            const $this = $(this);
            $this.removeClass(showClass);
            $this.find($dropdownToggle).attr("aria-expanded", "false");
            $this.children($dropdownMenu).removeClass(showClass);
          }
        );
      } else {
        $dropdown.off("mouseenter mouseleave");
      }
    });
    

    Source: https://webdesign.tutsplus.com/tutorials/how-to-make-the-bootstrap-navbar-dropdown-work-on-hover--cms-33840

提交回复
热议问题