Bootstrap: Open Another Modal in Modal

后端 未结 21 1020
难免孤独
难免孤独 2020-11-27 11:28

So, I\'m using this code to open another modal window in a current opened modal window:



        
21条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 11:50

    For bootstrap 4, to expand on @helloroy's answer I used the following;-

    var modal_lv = 0 ;
    $('body').on('shown.bs.modal', function(e) {
        if ( modal_lv > 0 )
        {
            $('.modal-backdrop:last').css('zIndex',1050+modal_lv) ;
            $(e.target).css('zIndex',1051+modal_lv) ;
        }
        modal_lv++ ;
    }).on('hidden.bs.modal', function() {
        if ( modal_lv > 0 )
            modal_lv-- ;
    });
    

    The advantage of the above is that it won't have any effect when there is only one modal, it only kicks in for multiples. Secondly, it delegates the handling to the body to ensure future modals which are not currently generated are still catered for.

    Update

    Moving to a js/css combined solution improves the look - the fade animation continues to work on the backdrop;-

    var modal_lv = 0 ;
    $('body').on('show.bs.modal', function(e) {
        if ( modal_lv > 0 )
            $(e.target).css('zIndex',1051+modal_lv) ;
        modal_lv++ ;
    }).on('hidden.bs.modal', function() {
        if ( modal_lv > 0 )
            modal_lv-- ;
    });
    

    combined with the following css;-

    .modal-backdrop ~ .modal-backdrop
    {
        z-index : 1051 ;
    }
    .modal-backdrop ~ .modal-backdrop ~ .modal-backdrop
    {
        z-index : 1052 ;
    }
    .modal-backdrop ~ .modal-backdrop ~ .modal-backdrop ~ .modal-backdrop
    {
        z-index : 1053 ;
    }
    

    This will handle modals nested up to 4 deep which is more than I need.

提交回复
热议问题