最近一直在用bootstrap开发前端,也是比较苦恼。
开发中纠结于没有公共的标准提示弹窗,所以只能自己写一个(能力不是很好。。第一次造轮子,也不知道算不算轮子)
下面是代码:
1.初始化模态框dom 用时间戳作为 模态框 id。用于区分多个弹窗的情况
//初始化模态框
var initWinModal = function(){
//加入时间戳随机数id 区分模态框id,这样可以同时调用多个模态提示框
pid += "-"+Date.now().toString(16);
$(document.body).append('<div id="'+pid+'" class="modal fade bs-example-modal-sm" aria-hidden="true" data-backdrop="static"></div>');
$("#"+pid).append('<div id="'+pid+'-body" class="modal-dialog modal-sm">'+
'<div class="modal-content">'+
'<div class="modal-header">'+
'<a id="'+pid+'-WinClose" class="close" data-dismiss="modal">'+_CONST.ualertContent.closeBtn+'</a>'+
'<h3 class="mah3">'+_CONST.ualertContent.title+'</h3>'+
'</div>'+
'<div id="'+pid+'-content" class="modal-body mabody">'+
'</div>'+
'<div class="modal-footer mafooter">'+
'<a id="'+pid+'-bSure" data-toggle="modal" data-dismiss="modal" class="btn mabun">'+_CONST.ualertContent.sureCn+'</a>'+
'<a id="'+pid+'-bClose" href="#" data-dismiss="modal" class="btn mabun">'+_CONST.ualertContent.closeCn+'</a>'+
'</div>'+
' </div>'+
'</div>');
initDomVar();
initContentBindButton();
};
2.弹窗按钮绑定,
//初始化提示内容,绑定弹窗控件
var initContentBindButton = function(){
//初始化提示内容
if(content === undefined || content === null){
content = "";
}
getDom.bmaContent().html("<p>"+content+"</p>");
//初始化按钮事件
//确定按钮
getDom.bmaButtonSure().unbind('click');
getDom.bmaButtonSure().on('click',function(){
_CONST.alertClickFlag = '0';
});
//窗口x关闭按钮
getDom.bmaButtonWinClose().unbind('click');
getDom.bmaButtonWinClose().on('click',function(){
_CONST.alertClickFlag = '1';
});
//关闭按钮
getDom.bmaButtonClose().unbind('click');
getDom.bmaButtonClose().on('click',function(){
_CONST.alertClickFlag = '1';
});
//隐藏窗口事件
getDom.bMsgAlert().off('hidden.bs.modal');
getDom.bMsgAlert().on('hidden.bs.modal', function(event) {
//移除dom
getDom.bMsgAlert().remove();
if(_CONST.alertClickFlag === '0'){
if(scb&&typeof(scb) === 'function'){
scb();
}
}else if(_CONST.alertClickFlag === '1'){
if(ccb&&typeof(ccb) === 'function'){
ccb();
}
}
});
};
最后是弹窗呈现
之前遇到了模态框多层嵌套的问题,网上找了大神的方法。而后我自己又做了部分改进(原贴地址再贴一遍:http://blog.csdn.net/k358971707/article/details/71908862)
改进地方是遍历后再多加一个属性做为分层区分:
//遍历排序模态框 用layer 区分模态框层
$('.modal.in').each(function(index) {
var $modal = $(this);
var layer = $modal.attr('layer');
if(!layer||layer === undefined){
$modal.attr('layer', $('.modal.in').length);
}
$modal.css('zIndex', modalZIndex+(parseFloat($modal.attr('layer'))));
});
//遍历排序模态框遮罩 用layer 区分模态框层
$('.modal-backdrop.in').each(function(index) {
$modalbackdrop = $(this);
var layer = $modalbackdrop.attr('layer');
if(!layer||layer === undefined){
$modalbackdrop.attr('layer', $('.modal-backdrop.in').length-1);
}
$modalbackdrop.addClass('hidden').css('zIndex', modalZIndex+(parseFloat($modalbackdrop.attr('layer'))));
if(index === $('.modal-backdrop.in').length-1){
$modalbackdrop.removeClass('hidden');
}
});
最后附上样例: