How to implement a Navbar Dropdown Hover in Bootstrap v4?

前端 未结 20 974
猫巷女王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

    Google brought me here but... The examples provided work if the dropdown menu is overlaping (at least by 1px) with its parent when show. If not, it loses focus and nothing works as intended.

    Here is a working solution with jQuery and Bootstrap 4.5.2 :

    $('li.nav-item').mouseenter(function (e) {
    
            e.stopImmediatePropagation();
    
            if ($(this).hasClass('dropdown')) {
    
                // target element containing dropdowns, show it
                $(this).addClass('show');
                $(this).find('.dropdown-menu').addClass('show');
    
                // Close dropdown on mouseleave
                $('.dropdown-menu').mouseleave(function (e) {
                    e.stopImmediatePropagation();
                    $(this).removeClass('show');
                });
    
                // If you have a prenav above, this clears open dropdowns (since you probably will hover the nav-item going up and it will reopen its dropdown otherwise)
                $('#prenav').off().mouseenter(function (e) {
                    e.stopImmediatePropagation();
                    $('.dropdown-menu').removeClass('show');
                });
    
            } else {
                // unset open dropdowns if hover is on simple nav element
                $('.dropdown-menu').removeClass('show');
            }
        });
    

提交回复
热议问题