基本調用: 自動關閉: 銷毀Loading Dom節點: ...
1 /** 2 * 自定義Loading插件 3 * @param {Object} config 4 * { 5 * content[載入顯示文本], 6 * time[自動關閉等待時間(ms)] 7 * } 8 * @param {String} config 9 * 載入顯示文本 10 * @refer 依賴 JQuery-1.9.1及以上、Bootstrap-3.3.7及以上 11 * @return {KZ_Loading} 對象實例 12 */ 13 function KZ_Loading(config) { 14 if (this instanceof KZ_Loading) { 15 const domTemplate = '<div class="modal fade kz-loading" data-kzid="@@KZ_Loadin_ID@@" backdrop="static" keyboard="false"><div style="width: 200px;height:20px; z-index: 20000; position: absolute; text-align: center; left: 50%; top: 50%;margin-left:-100px;margin-top:-10px"><div class="progress progress-striped active" style="margin-bottom: 0;"><div class="progress-bar" style="width: 100%;"></div></div><h5>@@KZ_Loading_Text@@</h5></div></div>'; 16 this.config = { 17 content: 'loading...', 18 time: 0, 19 }; 20 if (config != null) { 21 if (typeof config === 'string') { 22 this.config = Object.assign(this.config, { 23 content: config 24 }); 25 } else if (typeof config === 'object') { 26 this.config = Object.assign(this.config, config); 27 } 28 } 29 this.id = new Date().getTime().toString(); 30 this.state = 'hide'; 31 32 /*顯示 */ 33 this.show = function () { 34 $('.kz-loading[data-kzid=' + this.id + ']').modal({ 35 backdrop: 'static', 36 keyboard: false 37 }); 38 this.state = 'show'; 39 if (this.config.time > 0) { 40 var that = this; 41 setTimeout(function () { 42 that.hide(); 43 }, this.config.time); 44 } 45 }; 46 /*隱藏 */ 47 this.hide = function (callback) { 48 $('.kz-loading[data-kzid=' + this.id + ']').modal('hide'); 49 this.state = 'hide'; 50 if (callback) { 51 callback(); 52 } 53 }; 54 /*銷毀dom */ 55 this.destroy = function () { 56 var that = this; 57 this.hide(function () { 58 var node = $('.kz-loading[data-kzid=' + that.id + ']'); 59 node.next().remove(); 60 node.remove(); 61 that.show = function () { 62 throw new Error('對象已銷毀!'); 63 }; 64 that.hide = function () {}; 65 that.destroy = function () {}; 66 }); 67 } 68 69 var domHtml = domTemplate.replace('@@KZ_Loadin_ID@@', this.id).replace('@@KZ_Loading_Text@@', this.config.content); 70 $('body').append(domHtml); 71 } else { 72 return new KZ_Loading(config); 73 } 74 }
基本調用:
1 var loading = new KZ_Loading('數據載入中。。。'); 2 setTimeout(function () { 3 console.log('載入完成!'); 4 loading.hide(); 5 }, 1000);
自動關閉:
1 var loading = new KZ_Loading({ 2 content: '數據載入中。。。', 3 time: 2000 4 }); 5 loading.show();
銷毀Loading Dom節點:
1 loading.destroy();