How to implement a Navbar Dropdown Hover in Bootstrap v4?

前端 未结 20 999
猫巷女王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条回答
  •  旧时难觅i
    2020-12-02 06:30

    I had already used and styled a navbar when I was requested to change it to a hover interaction instead, so ended up with this as a fix using jQuery.

    function bootstrapHoverMenu (bp = 768) {
    
      // close all dropdowns that are open
        $('body').click( function (e) {
        $('.dropdown-menu.show').removeClass('show');
      });
    
      // show dropdown for the link clicked
      $('.nav-item').hover(function (e) {
        $('.dropdown-menu.show').removeClass('show');
        if(( $(window).width() >= bp )) {
          $dd = $(this).find('.dropdown-menu');
          $dd.addClass('show');
        }
      });
    
      // get href for top level link if clicked and open
      $('.dropdown').click(function (e) {
        if( $(window).width() < bp ) {
          $('.dropdown-menu').css({'display': 'none'});
        }
        $href = $(this).find('.nav-link').attr('href');
        window.open($href, '_self');
      });
    }
    
    $(document).ready( function() {
       // when page ready run the fix
       bootstrapHoverMenu();
    });
    

    Downside is mobile only has top level links.

提交回复
热议问题