[英]Bootstrap modal height as per window height
我試圖使模態高度與窗口高度相同。 模態的高度是動態的,可以適當地擴展以適應內容,最多可達窗口高度的 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 像素的高度。 比我關閉模態我將設備切換到橫向並打開模態,它顯示 430px(在縱向模式下的高度)但是如果我再次打開模態,它會得到正確的高度。
我認為當我關閉模態時,高度沒有被移除。 每次關閉模態或調整窗口大小時,我都必須寫一些清除高度的內容。
還試過:
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%。
在您的情況下,您只需要:
.modal {
height: 90vh;
}
如有必要,您也可以將其更改為max-height
。
您的回調函數更改了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 中的演示。
實際上我們需要使用 height 到.modal-body
以及overflow-y: auto
屬性,而不是.modal
。 但首先我們需要為.modal-header
和.modal-footer
留出一些空間。 所以,我將 75% 用於.modal-body
,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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.