bootstrap多个模态框嵌套显示,造成的遮罩颜色加深和页面滚动条问题
发布日期:2021-04-30 21:04:37 浏览次数:98 分类:精选文章

本文共 1562 字,大约阅读时间需要 5 分钟。

在 Bootstrap 的模态框功能中,当多个模态框同时存在时,通常会遇到一个问题:当用户关闭一个模态框后,滚动条会消失。这种情况可能是由于 Bootstrap 在模态框显示时会通过调整 bodypaddingz-index 来实现滚动条的效果。为了解决这个问题,我在大神的基础上对代码进行了优化。

具体来说,我通过检查当前页面是否还有其他模态框来决定是否需要重置 body 的样式。代码逻辑如下:

$(document).on('show.bs.modal', '.modal', function(event) {    $(this).appendTo($('body'));}).on('shown.bs.modal', '.modal.in', function(event) {    setModalsAndBackdropsOrder();}).on('hidden.bs.modal', '.modal', function(event) {    setModalsAndBackdropsOrder();});$.fn.modal.Constructor.prototype.hideModal = function() {    var that = this;    this.$element.hide();    this.backdrop(function() {        // 判断当前页面所有的模态框都已经隐藏了之后,重置 body 的样式        if ($('.modal.fade.in').length === 0) {            that.$body.removeClass('modal-open');            that.$body.css({                "padding": "8px 20px"            });        } else {            that.$body.addClass('modal-open');            that.$body.css({                "padding": "8px 20px"            });        }        that.resetAdjustments();        that.resetScrollbar();        that.$element.trigger('hidden.bs.modal');    });};function setModalsAndBackdropsOrder() {    var modalZIndex = 1040;    $('.modal.in').each(function(index) {        var $modal = $(this);        modalZIndex++;        $modal.css('zIndex', modalZIndex);        $modal.next('.modal-backdrop.in').addClass('hidden').css('zIndex', modalZIndex - 1);    });    $('.modal.in:visible:last').focus().next('.modal-backdrop.in').removeClass('hidden');}

通过以上优化,模态框的滚动条问题得到了有效解决。现在无论用户关闭哪个模态框,滚动条都会正确显示,同时所有模态框的 z-index 和布局也得到了合理的调整。

上一篇:【剑指offer】面试题29:顺时针打印矩阵(Java)
下一篇:DDD专栏开篇词:关于DDD

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2026年06月07日 06时47分02秒