bootstrap添加多个模态对话框支持

因为项目需要,在页面交互上要弹出多个dialog窗口,而bootstrap的modal支持弹出dialog窗口,但是如果在此基础上,会出现遮罩层越来越多,背景越来越黑的情况。

代码具体如下:

(function(){

modal = {};

modal.openDialog = function(url, title, width, height, id){};

modal.closeDialog = function(id){};

window.modal = modal;

})();

openDialog函数中传入了id,即为即将生成的dialog的div的id,url为dialog中iframe的src,id也将写在modal函数的参数option中。

调用多个dialog时,需要传入不同的id;

源代码中

backdrop: function (callback) {

var that = this

, animate = this.$element.hasClass('fade') ? 'fade' : ''

if (this.isShown && this.options.backdrop) {

var doAnimate = $.support.transition && animate

this.$backdrop = $(' ')

.appendTo(document.body)

this.$backdrop.click(

this.options.backdrop == 'static' ?

$.proxy(this.$element[0].focus, this.$element[0])

: $.proxy(this.hide, this)

)

if (doAnimate) this.$backdrop[0].offsetWidth // force reflow

this.$backdrop.addClass('in')

if (!callback) return

doAnimate ?

this.$backdrop.one($.support.transition.end, callback) :

callback()

} else if (!this.isShown && this.$backdrop) {

this.$backdrop.removeClass('in')

$.support.transition && this.$element.hasClass('fade')?

this.$backdrop.one($.support.transition.end, callback) :

callback()

} else if (callback) {

callback()

}

}

函数中 this.$backdrop = $(' ').appendTo(document.body)即为添加遮罩层。

遮罩层实现为在body后添加,并设置该div的z-Index为99999;

我们接下来的实现也是用z-Index,考虑到一层一层网上叠加z-Index,遮罩层只一个即可,而不同的dialog只需比遮罩层的z-Index高即可。

那就仅第一个dialog打开的时候添加遮罩层,其余时候对遮罩层的style中z-Index进行增大即可。

在Modal类代码中添加类对象,Modal.ids = [];

在进行添加遮罩层时,即var doAnimate = $.support.transition && animate 这行代码后对id进行push,再进行判断dialog个数

dialogId = option.id;

Modal.ids.push(id);

if(Modal.ids.length==1){

this.$backdrop = $(' ').appendTo(document.body);

$("#"+id).attr("style","z-Index:100000!important");

}else{

var perviouszIndex = $(".modal-backdrop").css("z-Index");

this.$backdrop = $(".modal-backdrop").attr("style","z-Index:"+(perviouszIndex+2)+"!important");

$("#"+id).attr("style","z-Index:"+(perviouszIndex+3)+"!important");

}

而当关闭时,需要对遮罩层的z-Index重新计算,dialog被隐藏了就不需要了,因为再次打开时会再次计算几次

关闭时,对遮罩层的操作在

removeBackdrop: function () {

this.$backdrop && this.$backdrop.remove()

this.$backdrop = null

}函数中,改写该函数即可

removeBackdrop: function () {

if(Modal.ids==1)

this.$backdrop && this.$backdrop.remove();

this.$backdrop = null;

Modal.ids.shift();

}else{

this.$backdrop.attr("style","z-Index:"+(perviouszIndex-2)+"!important");

Modal.ids.shift();

}