因为项目中使用的较多,因此封装了一个组件,便于使用。
/* *@file 弹框组件 *@description 用于所有提示弹框 *@time 2016/11/29 */ function PopModel(options) { var that = this; this.defaults = { '100px', // 默认框 height: '120px', // 默认高 isMask: true, // 是否遮罩 dir: 'mid', // mid中间,left左下,right右下 addClass: '', // 设置不同样式的class headHtml: '<button type="button" class="close">关闭</button>', // 头部,不需要直接设置为空 bodyHtml: '',// 内容 footHtml: '<input type="button" value="确定" class="confirm"><input type="button" value="取消" class="cancel">',// 底部,不需要直接设置为空 confireFn: function () {}, // 确认回调 cancelFn: function () {} // 取消回调 }; this.opts = $.extend({}, this.defaults, options); this.dialogWrap = $('<div class="dialog-wrap">'); this.modal = $('<div class="qbb-dialog ' + this.opts.addClass + '" style="position:fixed;border-radius:5px;background:#fff;z-index:99999;'+ this.opts.width+';height:'+ this.opts.height+'">'); this.header = $('<div class="modal-header">'); this.obody = $('<div class="modal-body">'); this.footer = $('<div class="modal-footer">'); this.mask = $('<div class="mask" style="position:fixed;left:0;top:0;100%;height:100%;z-index:9999;background:#000;opacity:0.5">'); // 遮罩 this.objDir(this.modal, this.opts.dir); if (this.opts.headHtml != '') { this.header.append(this.opts.headHtml); this.modal.append(this.header); } if (this.opts.bodyHtml != '') { this.obody.append(this.opts.bodyHtml); this.modal.append(this.obody); } if (this.opts.footHtml != '') { this.footer.append(this.opts.footHtml); this.modal.append(this.footer); } if (this.opts.isMask) { $(this.dialogWrap).append(this.mask); } this.dialogWrap.append(this.modal); $('body').append(this.dialogWrap); $(document).on('click', '.mask, .dialog-wrap .close', function () { that.closeFn(); }); $(this.footer).find('.confirm').on('click', function() { that.opts.confireFn(); that.closeFn(); }); $(this.footer).find('.cancel').on('click', function() { that.opts.cancelFn(); that.closeFn(); }) } PopModel.prototype = { constructor: PopModel, // 关闭函数 closeFn: function () { this.dialogWrap.remove(); }, // 位置函数 objDir: function (o, dir) { var w = $(o).outerWidth(true); var h = $(o).outerHeight(true); var winW = $(window).width(); var winH = $(window).height(); var oTop = ( winH - h )/2; var oLeft = ( winW - w )/2; if (dir == 'mid') { $(o).css({'left':oLeft, 'top':oTop}); } else if (dir == 'left') { $(o).css({'left':0, 'bottom':0}); } else if (dir == 'right') { $(o).css({'right':0, 'bottom':0}); } } }
调用:
new PopModel({});