jquery 实现loading
通常function 的方法名称大写 代表时构造函数。需要通过new 关键字调用。
function ShowLoading(opt) { //默认配置项 var _default = { "target": "body", //需要展示的遮罩的目标 "cssName": "_showloading", //class名称,可以自定义class "loadingImg": "/static/themes/vocs/ui-images/loading.gif", //遮罩图片的路径 "loadingText": "数据正在加载,请稍后...", //提示层的提示文字 "hideCall": null, //关闭回调函数 "timeout": 0 //是否自动关闭 }; $.extend(this, _default, opt); if (typeof this.target == "string") this.target = $(this.target); if (typeof context != 'undefined') this.loadingImg = context + this.loadingImg; var me = this; var isBody = $(me.target).prop("nodeName") == "BODY"; //获取目标的大小 var getSize = function () { var scrollTop = isBody ? $(window).scrollTop() : $(me.target).scrollTop(); var scrollLeft = isBody ? $(window).scrollLeft() : $(me.target).scrollLeft(); //var w = isBody ? (scrollLeft+$(window).width()) : (scrollLeft+$(me.target).width()); //var h = isBody ? (scrollTop + $(window).height()) : (scrollTop + $(me.target).height()); var w = isBody ? ($(window).width()) : ($(me.target).width()); var h = isBody ? ($(window).height()) : ($(me.target).height()); return {width: w, height: h, scrollTop: scrollTop, scrollLeft: scrollLeft}; } var setPsIntv; var $loading; this.show = function (msg, callBack) { if (!$loading) { this.loadingId = "_load" + (new Date()).valueOf(); if (!isBody) $(me.target).css("position", "relative"); $loading = $("<div>", { "id": this.loadingId, "class": this.cssName, //"style": "border:1px solid red", "html": "<div class='" + this.cssName + "-msg' style='background-image:url(" + this.loadingImg + ");background-repeat: no-repeat;background-position: 5px 10px;text-indent:25px;'>" + this.loadingText + "</div>" }).appendTo(this.target); var setPostion = function () { $loading.css({ // width: getSize().width + "px", width: getSize().width + "px", height: getSize().height + "px", top: getSize().scrollTop + "px", left: getSize().scrollLeft + "px" }); var sefWidth = $loading.children().width(), sefHeight = $loading.children().height(); $loading.children().css({ "top": function () { return parseInt((getSize().height- sefHeight) / 2) + "px" }, "left": function () { return parseInt((getSize().width - sefWidth) / 2) + "px" } }) } setPsIntv = setInterval(function () { setPostion(); }, 50); } if (msg){ this.loadingText = msg; $loading.children().text(msg); } //是否有回调函数 if (callBack != undefined && typeof callBack == "function") { this.hideCall = callBack; } //是否是定时关闭 if (this.timeout > 0) { setTimeout(function () { me.hide(); }, this.timeout); } return this; }; this.hide = function () { if ($loading) { $loading.remove(); } if (typeof this.hideCall=="function") { this.hideCall(); } if (setPsIntv) clearInterval(setPsIntv); }; }
这是构造函数 使用方式如下
var loading=new ShowLoading(); loading.show();
为了不写new 我们通常这样:
function showLoading(opt) { var loading = new ShowLoading(opt); loading.show(); return loading; }
每次调用就很方便了:
var loading = showLoading(); setTimeout(function () { loading.hide(); }, 1500);
技术交流QQ群:15129679