How to append a single dropdown menu to body in Bootstrap

后端 未结 3 1730
走了就别回头了
走了就别回头了 2021-02-19 22:48

I\'ve seen the documentation for the dropdown menu as component and separately using javascript.

I\'m wondering if it is possible to add a single dropdown menu in the we

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-19 23:17

    As the bootstrap documents say, there are no options for dropdown menus... This is sad, but it means there is currently not a 'bootstrap' solution for the functionality you want. There is now, however, a solution in the Angular-UI/Bootstrap kit if you're using that. The ticket you referenced is closed because it was finally added to the Angular-UI as of July 15th 2015.

    All you have to do is 'Add dropdown-append-to-body to the dropdown element to append to the inner dropdown-menu to the body. This is useful when the dropdown button is inside a div with overflow: hidden, and the menu would otherwise be hidden.' (reference)

    
    

    Hope this helps!


    EDIT

    In an effort to answer another SO question, I found a solution that works pretty well if you weren't using Angular-UI. It may be 'hacky', but it doesn't break the bootstrap menu functionality, and it seems to play well with most use cases I've used it for.

    So I'll leave a few fiddles in case anyone else sees this and is interested. The first illustrates why the use of a body appended menu might be nice, the second shows the working solution:

    Problem FIDDLE

    The problem: a select dropdown within a panel body

    
    

    Solution FIDDLE

    (function () {
        // hold onto the drop down menu                                             
        var dropdownMenu;
    
        // and when you show it, move it to the body                                     
        $(window).on('show.bs.dropdown', function (e) {
    
            // grab the menu        
            dropdownMenu = $(e.target).find('.dropdown-menu');
    
            // detach it and append it to the body
            $('body').append(dropdownMenu.detach());
    
            // grab the new offset position
            var eOffset = $(e.target).offset();
    
            // make sure to place it where it would normally go (this could be improved)
            dropdownMenu.css({
                'display': 'block',
                    'top': eOffset.top + $(e.target).outerHeight(),
                    'left': eOffset.left
            });
        });
    
        // and when you hide it, reattach the drop down, and hide it normally                                                   
        $(window).on('hide.bs.dropdown', function (e) {
            $(e.target).append(dropdownMenu.detach());
            dropdownMenu.hide();
        });
    })();
    

    EDIT I finally found where I originally found this solution. Gotta give credit where credit is due!

提交回复
热议问题