Bootstrap 3 - 根据屏幕尺寸设置模态窗口的高度

Ral*_*ser 54 css jquery twitter-bootstrap

我正在尝试使用Bootstrap 3模态对话框创建一种响应式megamenu.我想将整个模态窗口的宽度和高度设置为视口的80%,同时将模态体设置为最大高度,以便不在大视口上填充整个屏幕.

我的HTML:

    <div class="modal fade">
            <div class="modal-dialog modal-megamenu">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
                        <h4 class="modal-title">Modal Mega Menu Test</h4>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-3"></div>
                            <div class="col-md-3"></div>
                            <div class="col-md-3"></div>
                            <div class="col-md-3"></div>
                        </div>
                    </div>
                </div>
                    <div class="modal-footer">
                        <button type="button" data-dismiss="modal" class="btn btn-primary">close</button>
                    </div>
             </div>
        </div>
Run Code Online (Sandbox Code Playgroud)

我的CSS:

.modal-megamenu {
    width:80%;
    height:80%;
}

.modal-body {
    max-height:500px;
    overflow:auto;
}
Run Code Online (Sandbox Code Playgroud)

这适用于宽度,但"height"参数不会给出任何结果.像这样,模态窗口的高度始终设置为max-height值.有没有人知道如何根据视口高度动态设置高度?

Dan*_*hka 76

纯CSS解决方案,使用calc

.modal-body {
    max-height: calc(100vh - 200px);
    overflow-y: auto;
}
Run Code Online (Sandbox Code Playgroud)

可以根据页眉和页脚的高度调整200px

  • Son-of-a ....我一直在用JS做窗口调整大小的监听器*如何*长?!?我不知道`vh`单位存在.非常感谢! (2认同)

Rya*_*son 45

与Bass类似,我不得不设置溢出-y.这实际上可以在CSS中完成

$('#myModal').on('show.bs.modal', function () {
    $('.modal .modal-body').css('overflow-y', 'auto'); 
    $('.modal .modal-body').css('max-height', $(window).height() * 0.7);
});
Run Code Online (Sandbox Code Playgroud)


Bas*_*sen 31

尝试:

$('#myModal').on('show.bs.modal', function () {
$('.modal-content').css('height',$( window ).height()*0.8);
});
Run Code Online (Sandbox Code Playgroud)

  • 因为问题要求:"将整个模态窗口的宽度和高度设置为视口的80%".100%使用1,依此类推 (3认同)
  • 为了澄清,这只需要在`.modal('show')`命令之前,如果使用的话. (2认同)

Tia*_*ago 6

要扩展Ryand的答案,如果你使用的是Bootstrap.ui,那么在你的modal-instance上就能解决这个问题:

    modalInstance.rendered.then(function (result) {
        $('.modal .modal-body').css('overflow-y', 'auto'); 
        $('.modal .modal-body').css('max-height', $(window).height() * 0.7);
        $('.modal .modal-body').css('height', $(window).height() * 0.7);
    });
Run Code Online (Sandbox Code Playgroud)