自举模态高度(根据窗口高度) [英] Bootstrap modal height as per window height
问题描述
我正在尝试使模态高度与窗口高度相同.然后,模态的高度是动态的,可以扩展以适合内容,最高可达窗口高度的90%.还希望在屏幕顶部保留一些空间以显示标题.
I am trying to make modal height same as window height. The height of the modal is then dynamic, expanding to fit the content appropriately, up to 90% of the window height. Also want to left out some space top of the screen to show the header.
这是我写的:
$(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);
}
});
})
问题是当我将设备从纵向切换为横向或从横向切换为横向时,第一次尝试模态会获得上一个模式的高度.
Problem is when i switch the device from portrait to landscape or vice versa, on the first attempt modal gets height of previous mode.
可以说我在肖像模式下打开了模态,它的高度为430px.比起我关闭模态,我将设备切换到横向并打开模态,它显示430px(在纵向模式下出现的高度),但是如果我再次打开模态,它将获得正确的高度.
Lets say i open the modal on portait mode and it is shwoing 430px of height. Than i closed the modal i switch the device to landscape and open the modal, it shows 430px(height that were coming on portait mode) but if i again open the modal, it gets the correct height.
我认为当我关闭模态时,高度并没有消除.每次我关闭模态或调整窗口大小时,我都必须写一些清除高度的东西.
I think when i close the modal the height didn't get remove. I have to write something that clear the height every time i close the modal or resize the window.
也尝试过:
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);
推荐答案
如果您希望模态消耗90%的视口高度,则不需要任何JS.CSS有一个特殊的单元,称为 vh
. 100vh
是视口的100%.
If you want the modal to consume 90% of the viewport height, you don't need any JS. CSS has a special unit for that called vh
. 100vh
is 100% of the viewport.
就您而言,您只需要:
.modal {
height: 90vh;
}
如果需要,您也可以将其更改为 max-height
.
You can also change it to max-height
if necessary.
这篇关于自举模态高度(根据窗口高度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!