自定义展示加载等待图片插件(loading.git)

自定义显示加载等待图片插件(loading.git)

 

在工作中遇到了一个问题 —— 某个业务流程分为几个阶段,每个阶段如果在数据没有显示出来之前就要显示加载图片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>