You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置模态框(modal)内部div高度,实现内容超出时滚动效果

解决方案

优先推荐纯CSS实现方案,无需JS计算高度,兼容性和稳定性更好:

方案1:纯CSS实现(推荐)

修改对应样式如下:

/* 先确保模态框body高度铺满可用空间 */
#editSaga .modal-body {
    height: 100%;
}
.col-7.firstchild {
    max-height: 100%;
    overflow: hidden;
    /* 新增以下样式 */
    display: flex;
    flex-direction: column;
}
.firstchild-body2 {
    /* 占用剩余垂直空间 */
    flex: 1;
    /* 内容超出时滚动 */
    overflow-y: auto;
}

方案2:修正原jQuery实现

你原来的代码存在多处语法和逻辑错误,修正后可正常运行:

  1. 先给.firstchild-body2加基础样式:
.firstchild-body2 {
    overflow-y: auto;
}
  1. 修正JS代码,要等模态框完全渲染后再计算高度:
// 绑定bootstrap模态框显示完成事件,确保能拿到正确的元素高度
$('#editSaga').on('shown.bs.modal', function() {
    const totalHeight = $('.col-7.firstchild').height();
    const headerHeight = $('.firstchild-header').outerHeight(true);
    const body1Height = $('.firstchild-body1').outerHeight(true);
    // 计算body2可用高度,留2px冗余避免误差
    const body2Height = totalHeight - headerHeight - body1Height - 2;
    $('.firstchild-body2').height(body2Height);
})

内容的提问来源于stack exchange,提问作者Papis Sahine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 07:24:08