您的位置:首页 > Web前端 > BootStrap

js 重写 bootstrap 样式 alert/confirm 消息窗口

2016-02-02 17:04 489 查看
相信很多人都受够了 alert、confirm 的样子,最近正在用 bootstrap 做项目,顺便封装了一个 bootstrap 样式的消息框。

实现起来很简单,bootstrap 本身就自带了 modal 模态框,样子还不错 :)就把它封装一下用吧。

无码无真相,少说多做,上代码。直接在全局 Layout 页面加上以下HTML:

<!-- system modal start -->
<div id="ycf-alert" class="modal">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h5 class="modal-title"><i class="fa fa-exclamation-circle"></i> [Title]</h5>
</div>
<div class="modal-body small">
<p>[Message]</p>
</div>
<div class="modal-footer" >
<button type="button" class="btn btn-primary ok" data-dismiss="modal">[BtnOk]</button>
<button type="button" class="btn btn-default cancel" data-dismiss="modal">[BtnCancel]</button>
</div>
</div>
</div>
</div>
<!-- system modal end -->


js 封装如下:

$(function () {
window.Modal = function () {
var reg = new RegExp("\\[([^\\[\\]]*?)\\]", 'igm');
var alr = $("#ycf-alert");
var ahtml = alr.html();

//关闭时恢复 modal html 原样,供下次调用时 replace 用
//var _init = function () {
//  alr.on("hidden.bs.modal", function (e) {
//      $(this).html(ahtml);
//  });
//}();

/* html 复原不在 _init() 里面做了,重复调用时会有问题,直接在 _alert/_confirm 里面做 */

var _alert = function (options) {
alr.html(ahtml);  // 复原
alr.find('.ok').removeClass('btn-success').addClass('btn-primary');
alr.find('.cancel').hide();
_dialog(options);

return {
on: function (callback) {
if (callback && callback instanceof Function) {
alr.find('.ok').click(function () { callback(true) });
}
}
};
};

var _confirm = function (options) {
alr.html(ahtml); // 复原
alr.find('.ok').removeClass('btn-primary').addClass('btn-success');
alr.find('.cancel').show();
_dialog(options);

return {
on: function (callback) {
if (callback && callback instanceof Function) {
alr.find('.ok').click(function () { callback(true) });

}
}
};
};

var _dialog = function (options) {
var ops = {
msg: "提示内容",
title: "操作提示",
btnok: "确定",
btncl: "取消"
};

$.extend(ops, options);

console.log(alr);

var html = alr.html().replace(reg, function (node, key) {
return {
Title: ops.title,
Message: ops.msg,
BtnOk: ops.btnok,
BtnCancel: ops.btncl
}[key];
});

alr.html(html);
alr.modal({
width: 500,
backdrop: 'static'
});
}

return {
alert: _alert,
confirm: _confirm
}

}();
});


调用方法:

function userDel(id){
Modal.confirm(
{
msg: "是否删除角
9669
色?"
})
.on( function (e) {
$.ajax({
url:"__CONTROLLER__/userDel",
type:"post",
data:"id=" + id,
dataType:"JSON" ,
success:function(res){

Modal.alert(
{
msg: res['msg'],
title: '操作',
btnok: '确定',
btncl:'取消'
});
if(res['status']=='success'){
$('#' + id).remove();
}
}
})
});
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  bootstrap javascript html