本文實例講述了JS實現的自定義顯示加載等待圖片插件。分享給大家供大家參考,具體如下:
在工作中遇到了一個問題 —— 某個業務流程分為幾個階段,每個階段如果在數據沒有顯示出來之前就要顯示加載圖片loading.gif文件,如果有數據了就消失。為此,自己寫了一個方法,方便整個工程使用。
<button onclick="show()">show</button>
<button onclick="hide()">hide</button>
<script>
//創建加載對象
var obj = new loadingImg();
//顯示加載圖片
function show(){
obj.show();
}
//隱藏加載圖片
function hide(){
obj.hide();
}
//加載圖片方法(對象)
function loadingImg(mySetting){
var that = this;
if(mySetting == "" || mySetting == undefined || typeof mySetting != "object"){
mySetting = {};
}
//使用時間戳作為空間的ID
var targetID = new Date().getTime();
this.setting = {
//插入圖片的容器,使用jquery的查詢方式傳入參數
targetConater : "",
//使用圖片的地址
imgUrl : "../img/loading.gif",
//圖片顯示的 寬度
imgWidth : "32px",
//圖片的默認樣式
imgClass : "",
//生成控件的ID
"targetID" : targetID,
//顯示之前的回調函數
beforeShow : function(plugin){
},
//顯示之後的回調函數
afterShow : function(plugin,targetID){
}
}
this.setting = $.extend(this.setting, mySetting);
//獲取屏幕的寬度
this.getScreenWidth = function(){
return document.documentElement.clientWidth;
}
//獲取屏幕的高度
this.getScreenHeight = function (){
return document.documentElement.clientHeight;
}
//顯示控件
this.show = function(){
$("#" + that.setting.targetID).show();
}
//隱藏控件
this.hide = function(){
$("#" + that.setting.targetID).hide();
}
this.init = function(){
//顯示之前執行回調函數
if(typeof that.setting.beforeShow == "function"){
that.setting.beforeShow(that);
}
//存放字符串的變量
var targetHTML = '';
//將內容存放到指定的容器中,默認存放到body最底部
if(that.setting.targetConater != "" && this.setting.targetConater != undefined){
targetHTML = '<img src="' + that.setting.imgUrl + '" class="' + that.setting.imgClass + '" id="' + that.setting.targetID + '" style="display:none;">';
$(that.setting.targetConater).html(targetHTML);
}else{
targetHTML = '<img src="' + that.setting.imgUrl + '" class="' + that.setting.imgClass + '">';
targetHTML = '<div id="' + that.setting.targetID + '" style="display:none;position: absolute;top:50%;left: 50%;height: ' + that.getScreenHeight()+';width:'+that.getScreenWidth()+'">' + targetHTML + '</div>';
$("body").append(targetHTML);
}
//判斷用戶是否自定義了圖片的寬度
if(that.setting.imgWidth != "" && that.setting.imgWidth.indexOf("px")>0 ){
$("#"+targetID).css("width",that.setting.imgWidth);
}
//顯示之後執行回調函數
if(typeof that.setting.afterShow == "function"){
that.setting.afterShow(that,targetID);
}
}
this.init();
}
</script>
更多關於JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript切換特效與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。