(轉自Bootstrap:彈出框和提示框效果以及代碼展示)
前言:對于Web開發人員,彈出框和提示框的使用肯定不會陌生,比如常見的表格新增和編輯功能,一般常見的主要有兩種處理方式:行内編輯和彈出框編輯。在增加使用者體驗方面,彈出框和提示框起着重要的作用,如果你的系統有一個友好的彈出提示框,自然能給使用者很好的頁面體驗。前面幾章介紹了bootstrap的幾個常用元件,這章來看看bootstrap裡面彈出框和提示框的處理。總的來說,彈出提示主要分為三種:彈出框、确定取消提示框、資訊提示框。本篇就結合這三種類型分别來介紹下它們的使用。
一、Bootstrap彈出框
使用過JQuery UI的園友們應該知道,它裡面有一個dialog的彈出框元件,功能也很豐富。與jQuery UI的dialog類似,Bootstrap裡面也内置了彈出框元件。打開bootstrap 文檔http://v3.bootcss.com/components/可以看到它的dialog是直接嵌入到bootstrap.js和bootstrap.css裡面的,也就是說,隻要我們引入了bootstrap的檔案,就可以直接使用它的dialog元件,是不是很友善。本篇我們就結合新增編輯的功能來介紹下bootstrap dialog的使用。廢話不多說,直接看來它如何使用吧。
1、cshtml界面代碼
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLrN2bsJEZlR3YhJHdu92Qvw1cy9GdhNWak5WSn5WaulGb0V3TvwVbvNmLzd2bsJmbj5ycldWYtl2Lc9CX6MHc0RHaiojIsJye.gif)
1 <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
2 <div class="modal-dialog" role="document">
3 <div class="modal-content">
4 <div class="modal-header">
5 <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
6 <h4 class="modal-title" id="myModalLabel">新增</h4>
7 </div>
8 <div class="modal-body">
9
10 <div class="form-group">
11 <label for="txt_departmentname">部門名稱</label>
12 <input type="text" name="txt_departmentname" class="form-control" id="txt_departmentname" placeholder="部門名稱">
13 </div>
14 <div class="form-group">
15 <label for="txt_parentdepartment">上級部門</label>
16 <input type="text" name="txt_parentdepartment" class="form-control" id="txt_parentdepartment" placeholder="上級部門">
17 </div>
18 <div class="form-group">
19 <label for="txt_departmentlevel">部門級别</label>
20 <input type="text" name="txt_departmentlevel" class="form-control" id="txt_departmentlevel" placeholder="部門級别">
21 </div>
22 <div class="form-group">
23 <label for="txt_statu">描述</label>
24 <input type="text" name="txt_statu" class="form-control" id="txt_statu" placeholder="狀态">
25 </div>
26 </div>
27 <div class="modal-footer">
28 <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>關閉</button>
29 <button type="button" id="btn_submit" class="btn btn-primary" data-dismiss="modal"><span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span>儲存</button>
30 </div>
31 </div>
32 </div>
33 </div>
View Code
最外面的div定義了dialog的隐藏。我們重點來看看第二層的div
1 <div class="modal-dialog" role="document">
這個div定義了dialog,對應的class有三種尺寸的彈出框,如下:
1 <div class="modal-dialog" role="document">
1 <div class="modal-dialog modal-lg" role="document">
1 <div class="modal-dialog modal-full" role="document">
第一種表示預設類型的彈出框;第二種表示增大的彈出框;第三種表示滿屏的彈出框。role="document"表示彈出框的對象的目前的document。
2、js裡面将dialog show出來。
預設情況下,我們的彈出框是隐藏的,隻有在使用者點選某個操作的時候才會show出來。來看看js裡面是如何處理的吧:
1 //注冊新增按鈕的事件
2 $("#btn_add").click(function () {
3 $("#myModalLabel").text("新增");
4 $('#myModal').modal();
5 });
對,你沒有看錯,隻需要這一句就能show出這個dialog。
$('#myModal').modal();
3、效果展示
新增效果
編輯效果
4、說明
彈出框顯示後,點選界面上其他地方以及按Esc鍵都能隐藏彈出框,這樣使得使用者的操作更加友好。關于dialog裡面關閉和儲存按鈕的事件的初始化在項目裡面一般是封裝過的,這個我們待會來看。
二、确認取消提示框
這種類型的提示框一般用于某些需要使用者确定才能進行的操作,比較常見的如:删除操作、送出訂單操作等。
1、使用bootstrap彈出框确認取消提示框
介紹這個元件之前,就得說說元件封裝了,我們知道,像彈出框、确認取消提示框、資訊提示框這些東西項目裡面肯定是多處都要調用的,是以我們肯定是要封裝元件的。下面就來看看我們封裝的缺乏取消提示框。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLrN2bsJEZlR3YhJHdu92Qvw1cy9GdhNWak5WSn5WaulGb0V3TvwVbvNmLzd2bsJmbj5ycldWYtl2Lc9CX6MHc0RHaiojIsJye.gif)
1 (function ($) {
2
3 window.Ewin = function () {
4 var html = '<div id="[Id]" class="modal fade" role="dialog" aria-labelledby="modalLabel">' +
5 '<div class="modal-dialog modal-sm">' +
6 '<div class="modal-content">' +
7 '<div class="modal-header">' +
8 '<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>' +
9 '<h4 class="modal-title" id="modalLabel">[Title]</h4>' +
10 '</div>' +
11 '<div class="modal-body">' +
12 '<p>[Message]</p>' +
13 '</div>' +
14 '<div class="modal-footer">' +
15 '<button type="button" class="btn btn-default cancel" data-dismiss="modal">[BtnCancel]</button>' +
16 '<button type="button" class="btn btn-primary ok" data-dismiss="modal">[BtnOk]</button>' +
17 '</div>' +
18 '</div>' +
19 '</div>' +
20 '</div>';
21
22
23 var dialogdHtml = '<div id="[Id]" class="modal fade" role="dialog" aria-labelledby="modalLabel">' +
24 '<div class="modal-dialog">' +
25 '<div class="modal-content">' +
26 '<div class="modal-header">' +
27 '<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>' +
28 '<h4 class="modal-title" id="modalLabel">[Title]</h4>' +
29 '</div>' +
30 '<div class="modal-body">' +
31 '</div>' +
32 '</div>' +
33 '</div>' +
34 '</div>';
35 var reg = new RegExp("\\[([^\\[\\]]*?)\\]", 'igm');
36 var generateId = function () {
37 var date = new Date();
38 return 'mdl' + date.valueOf();
39 }
40 var init = function (options) {
41 options = $.extend({}, {
42 title: "操作提示",
43 message: "提示内容",
44 btnok: "确定",
45 btncl: "取消",
46 width: 200,
47 auto: false
48 }, options || {});
49 var modalId = generateId();
50 var content = html.replace(reg, function (node, key) {
51 return {
52 Id: modalId,
53 Title: options.title,
54 Message: options.message,
55 BtnOk: options.btnok,
56 BtnCancel: options.btncl
57 }[key];
58 });
59 $('body').append(content);
60 $('#' + modalId).modal({
61 width: options.width,
62 backdrop: 'static'
63 });
64 $('#' + modalId).on('hide.bs.modal', function (e) {
65 $('body').find('#' + modalId).remove();
66 });
67 return modalId;
68 }
69
70 return {
71 alert: function (options) {
72 if (typeof options == 'string') {
73 options = {
74 message: options
75 };
76 }
77 var id = init(options);
78 var modal = $('#' + id);
79 modal.find('.ok').removeClass('btn-success').addClass('btn-primary');
80 modal.find('.cancel').hide();
81
82 return {
83 id: id,
84 on: function (callback) {
85 if (callback && callback instanceof Function) {
86 modal.find('.ok').click(function () { callback(true); });
87 }
88 },
89 hide: function (callback) {
90 if (callback && callback instanceof Function) {
91 modal.on('hide.bs.modal', function (e) {
92 callback(e);
93 });
94 }
95 }
96 };
97 },
98 confirm: function (options) {
99 var id = init(options);
100 var modal = $('#' + id);
101 modal.find('.ok').removeClass('btn-primary').addClass('btn-success');
102 modal.find('.cancel').show();
103 return {
104 id: id,
105 on: function (callback) {
106 if (callback && callback instanceof Function) {
107 modal.find('.ok').click(function () { callback(true); });
108 modal.find('.cancel').click(function () { callback(false); });
109 }
110 },
111 hide: function (callback) {
112 if (callback && callback instanceof Function) {
113 modal.on('hide.bs.modal', function (e) {
114 callback(e);
115 });
116 }
117 }
118 };
119 },
120 dialog: function (options) {
121 options = $.extend({}, {
122 title: 'title',
123 url: '',
124 width: 800,
125 height: 550,
126 onReady: function () { },
127 onShown: function (e) { }
128 }, options || {});
129 var modalId = generateId();
130
131 var content = dialogdHtml.replace(reg, function (node, key) {
132 return {
133 Id: modalId,
134 Title: options.title
135 }[key];
136 });
137 $('body').append(content);
138 var target = $('#' + modalId);
139 target.find('.modal-body').load(options.url);
140 if (options.onReady())
141 options.onReady.call(target);
142 target.modal();
143 target.on('shown.bs.modal', function (e) {
144 if (options.onReady(e))
145 options.onReady.call(target, e);
146 });
147 target.on('hide.bs.modal', function (e) {
148 $('body').find(target).remove();
149 });
150 }
151 }
152 }();
153 })(jQuery);
154
155 元件封裝
不了解元件封裝的朋友可以先看看相關文章。這裡我們的确認取消提示框主要用到了confirm這個屬性對應的方法。還是來看看如何調用吧:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLrN2bsJEZlR3YhJHdu92Qvw1cy9GdhNWak5WSn5WaulGb0V3TvwVbvNmLzd2bsJmbj5ycldWYtl2Lc9CX6MHc0RHaiojIsJye.gif)
1 //注冊删除按鈕的事件
2 $("#btn_delete").click(function () {
3 //取表格的選中行資料
4 var arrselections = $("#tb_departments").bootstrapTable('getSelections');
5 if (arrselections.length <= 0) {
6 toastr.warning('請選擇有效資料');
7 return;
8 }
9
10 Ewin.confirm({ message: "确認要删除選擇的資料嗎?" }).on(function (e) {
11 if (!e) {
12 return;
13 }
14 $.ajax({
15 type: "post",
16 url: "/api/DepartmentApi/Delete",
17 data: { "": JSON.stringify(arrselections) },
18 success: function (data, status) {
19 if (status == "success") {
20 toastr.success('送出資料成功');
21 $("#tb_departments").bootstrapTable('refresh');
22 }
23 },
24 error: function () {
25 toastr.error('Error');
26 },
27 complete: function () {
28
29 }
30
31 });
32 });
33 });
message屬性傳入提示的資訊,on裡面注入點選按鈕後的回調事件。
生成的效果:
2、bootbox元件的使用
在網上找bootstrap的彈出元件時總是可以看到bootbox這麼一個東西,确實是一個很簡單的元件,還是來看看如何使用吧。
bootbox API:http://bootboxjs.com/documentation.html
當然要使用它必須要添加元件喽。無非也是兩種方式:引入源碼和Nuget。
接下來就是使用它了。首先當然是添加bootbox.js的引用了。然後就是在相應的地方調用了。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLrN2bsJEZlR3YhJHdu92Qvw1cy9GdhNWak5WSn5WaulGb0V3TvwVbvNmLzd2bsJmbj5ycldWYtl2Lc9CX6MHc0RHaiojIsJye.gif)
1 $("#btn_delete").click(function () {
2 var arrselections = $("#tb_departments").bootstrapTable('getSelections');
3 if (arrselections.length <= 0) {
4 toastr.warning('請選擇有效資料');
5 return;
6 }
7
8 bootbox.alert("确認删除", function () {
9 var strResult = "";
10 })
11 bootbox.prompt("确認删除", function (result) {
12 var strResult = result;
13 })
14 bootbox.confirm("确認删除", function (result) {
15 var strResult = result;
16 })
17
18 });
效果展示:
更多用法可以參見api。使用起來基本很簡單。這個元件最大的特點就是和bootstrap的風格能夠很好的保持一緻。
3、在網上還找到一個效果比較炫一點的提示框:sweetalert
要使用它,還是老規矩:Nuget。
(1)文檔
sweetalert Api:http://t4t5.github.io/sweetalert/
開源項目源碼:https://github.com/t4t5/sweetalert
(2)在cshtml頁面引入js和css
1 <link href="~/Styles/sweetalert.css" rel="stylesheet" />
2 <script src="~/Scripts/sweetalert.min.js"></script>
(3)js使用
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLrN2bsJEZlR3YhJHdu92Qvw1cy9GdhNWak5WSn5WaulGb0V3TvwVbvNmLzd2bsJmbj5ycldWYtl2Lc9CX6MHc0RHaiojIsJye.gif)
1 swal({
2 title: "操作提示", //彈出框的title
3 text: "确定删除嗎?", //彈出框裡面的提示文本
4 type: "warning", //彈出框類型
5 showCancelButton: true, //是否顯示取消按鈕
6 confirmButtonColor: "#DD6B55",//确定按鈕顔色
7 cancelButtonText: "取消",//取消按鈕文本
8 confirmButtonText: "是的,确定删除!",//确定按鈕上面的文檔
9 closeOnConfirm: true
10 }, function () {
11 $.ajax({
12 type: "post",
13 url: "/Home/Delete",
14 data: { "": JSON.stringify(arrselections) },
15 success: function (data, status) {
16 if (status == "success") {
17 toastr.success('送出資料成功');
18 $("#tb_departments").bootstrapTable('refresh');
19 }
20 },
21 error: function () {
22 toastr.error('Error');
23 },
24 complete: function () {
25
26 }
27
28 });
29 });
(4)效果展示:
點選确定後進入回調函數:
元件很多,用哪種園友沒可以自行決定,不過部落客覺得像一些網際網路、電子商務類型的網站用sweetalert效果比較合适,一般的内部系統可能也用不上。
三、操作完成提示框
1、toastr.js元件
關于資訊提示框,部落客項目中使用的是toastr.js這麼一個元件,這個元件最大的好處就是異步、無阻塞,提示後可設定消失時間,并且可以将消息提示放到界面的各個地方。先來看看效果。
官方文檔以及源碼
源碼網站:http://codeseven.github.io/toastr/
api:http://www.ithao123.cn/content-2414918.html
關于它的使用。
(1)、引入js和css
1 <link href="~/Content/toastr/toastr.css" rel="stylesheet" />
2 <script src="~/Content/toastr/toastr.min.js"></script>
(2)、js初始化
1 <script type="text/javascript">
2 toastr.options.positionClass = 'toast-bottom-right';
3 </script>
将這個屬性值設定為不同的值就能讓提示資訊顯示在不同的位置,如toast-bottom-right表示下右、toast-bottom-center表示下中、toast-top-center表示上中等,更過位置資訊請檢視文檔。
(3)、使用
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLrN2bsJEZlR3YhJHdu92Qvw1cy9GdhNWak5WSn5WaulGb0V3TvwVbvNmLzd2bsJmbj5ycldWYtl2Lc9CX6MHc0RHaiojIsJye.gif)
1 //初始化編輯按鈕
2 $("#btn_edit").click(function () {
3 var arrselections = $("#tb_departments").bootstrapTable('getSelections');
4 if (arrselections.length > 1) {
5 toastr.warning('隻能選擇一行進行編輯');
6
7 return;
8 }
9 if (arrselections.length <= 0) {
10 toastr.warning('請選擇有效資料');
11
12 return;
13 }
14
15 $('#myModal').modal();
16 });
使用起來就如下一句:
1 toastr.warning('隻能選擇一行進行編輯');
是不是很簡單~~這裡的有四種方法分别對應四種不同顔色的提示框。
1 toastr.success('送出資料成功');
2 toastr.error('Error');
3 toastr.warning('隻能選擇一行進行編輯');
4 toastr.info('info');
分别對應上圖中的四種顔色的提示框。
2、Messenger元件
在Bootstrap中文網裡面提到了一個alert元件:Messenger。
它的使用和toastr.js這個元件基本相似,隻不過效果有點不太一樣。我們還是來看看它是如何使用的。
(1)效果展示
可以定位到網頁的不同位置,例如下圖中給出的下中位置、上中位置。
提示框的樣式有三種狀态:Success、Error、Info
并且支援四種不同樣式的提示框:Future、Block、Air、Ice
(2)元件使用以及代碼示例
Messenger Api文檔:http://www.bootcss.com/p/messenger/
Messenger 源碼:https://github.com/HubSpot/messenger
關于它的使用和toastr大同小異,首先引入元件:
1 <script src="~/Content/HubSpot-messenger-a3df9a6/build/js/messenger.js"></script>
2 <link href="~/Content/HubSpot-messenger-a3df9a6/build/css/messenger.css" rel="stylesheet" />
3 <link href="~/Content/HubSpot-messenger-a3df9a6/build/css/messenger-theme-future.css" rel="stylesheet" />
初始化它的位置
1 <script type="text/javascript">
2 $._messengerDefaults = {
3 extraClasses: 'messenger-fixed messenger-theme-future messenger-on-bottom messenger-on-right'
4 }
5 </script>
然後js裡面使用如下:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLrN2bsJEZlR3YhJHdu92Qvw1cy9GdhNWak5WSn5WaulGb0V3TvwVbvNmLzd2bsJmbj5ycldWYtl2Lc9CX6MHc0RHaiojIsJye.gif)
1 $("#btn_delete").click(function () {
2 $.globalMessenger().post({
3 message: "操作成功",//提示資訊
4 type: 'info',//消息類型。error、info、success
5 hideAfter: 2,//多長時間消失
6 showCloseButton:true,//是否顯示關閉按鈕
7 hideOnNavigate: true //是否隐藏導航
8 });
9 });
如果提示框使用預設樣式,也隻有一句就能解決
1 $.globalMessenger().post({
2 message: "操作成功",//提示資訊
3 type: 'info',//消息類型。error、info、success
4 });
很簡單很強大有木有~~
四、總結
以上就是部落客花了幾個小時時間整理出來的幾種常用bootstrap常用彈出和提示框的效果以及使用小結,雖然花了點時間,但想想值了。如果你覺得文章能或多或少幫到你,請幫忙推薦一下吧,畢竟有你的支援,部落客才有更大的動力。另外,如果園友們有什麼更好的的彈出提示元件,不吝賜教~~歡迎拍磚~~
鑒于園友提的一個問題,部落客将toastr元件加了一個居中顯示的效果,其實也很簡單,在此記錄下:
在toastr.css檔案中加一個樣式:
1 .toast-center-center {
2 top: 50%;
3 left: 50%;
4 margin-top: -25px;
5 margin-left: -150px;
6 }
然後在指定位置的時候
1 <script type="text/javascript">
2 toastr.options.positionClass = 'toast-center-center';
3 </script>
搞定,然後看看效果: