根据窗口高度设置Bootstrap模态框高度

9
我正在尝试使模态框的高度与窗口高度相同。模态框的高度是动态的,会根据内容适当地扩展,并且最多为窗口高度的90%。同时,想要在屏幕顶部留出一些空间来显示标题。以下是代码:
 $(document).ready(function(){
    $('.modal').on('shown.bs.modal', function (e) {
        var modalObj = $(this).find('.modal-content');                                        
        if ($(modalObj).height() > ($(window).height()*0.8)) {
            $(modalObj).height($(window).height()*0.8);
        }                                         
    });
 })

问题在于当我将设备从纵向模式切换到横向模式或反之时,第一次尝试打开模态框时,其高度会受到上一个模式的影响。
假设我在纵向模式下打开模态框,其高度为430像素。然后我关闭了模态框,将设备切换到横向模式并重新打开模态框,它显示的是430像素(即在纵向模式下显示的高度),但如果我再次打开模态框,则会得到正确的高度。
我认为关闭模态框时高度没有被清除。我需要编写一些代码,在每次关闭模态框或调整窗口大小时清除高度。
也尝试过:
var callback = function () {

  $('.modal').on('shown.bs.modal', function (e) {
        var modalObj = $(this).find('.modal-content');                                      
        if ($(modalObj).height() > ($(window).height()*0.9)) {
            $(modalObj).height($(window).height()*0.9);
        }                                         
    });
};

$(document).ready(callback);
$(window).resize(callback);

1
你想让模态框的高度占据视口高度的90%吗? - Gofilord
3个回答

19

如果您想让模态框占用90%的视口高度,您不需要任何JS。CSS具有一种特殊的单位,叫做vh100vh就是视口的100%。

对于您的情况,您只需要:

.modal {
  height: 90vh;
}
你如果需要的话,也可以把它改成max-height

这是一个不错的方法,可以保持模态容器的高度小于窗口宽度。但我必须在运行时计算模态内容的高度,以便在需要时应用滚动条。 - Praveen
1
使用以下代码:$('.modal').on('hidden.bs.modal', function (e) { $(this).find('.modal-content').height($(window).height()*0.9); }); - Praveen
你不需要 JS,我给你的代码跟你的 JS 做了同样的事情,并在每次视口更改时进行更新。 - Gofilord

3

您的回调函数更改了 shown.bs.modal 事件的处理程序。如果您的模态框已经打开,此处理程序已经执行过,并且不会在窗口调整大小时再次触发。

您需要为 window.resize 事件使用不同的处理程序。

// This will detect and set the height properly when the modal opens
$('.modal').on('shown.bs.modal', function (e) {
    var modalObj = $(this).find('.modal-content');
    $(modalObj).height('auto');
    if ($(modalObj).height() > ($(window).height() * 0.9)) {
        $(modalObj).height($(window).height() * 0.9);
    }
});

// This will detect and set the height properly when the window resizes
var callback = function () {
    jQuery('.modal').each(function (idx, item) {
        var modalObj = $(item).find('.modal-content');
        $(modalObj).height('auto');
        if ($(modalObj).height() > ($(window).height() * 0.9)) {
            $(modalObj).height($(window).height() * 0.9);
        }
    });
};

// Binding the callback in document.ready is not required, just on window.resize
$(window).resize(callback);

这里有一个在Bootply上的演示,点击这里

3
实际上,我们需要将高度应用到.modal-body,并搭配 overflow-y: auto 属性,而不是应用到.modal。但首先我们需要为.modal-header.modal-footer留出一些空间。因此,我将.modal-body设置为75%,留下25%给.modal-header.modal-footer。您可以根据需要进行调整。
.modal-body {
  max-height: 75vh;
  overflow-y: auto;
}

或者如果您想按像素进行调整

.modal-body {
   max-height: calc(100vh - 180px); // to adjust you can change 180px
   overflow-y: auto;
   }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接