jquery简单封装loading插件(一)

jquery目前是一般公司应用的最多的js插件,虽然不是最火的但是是比较成熟且经过大量实践检验的js插件。

###最近工作之余想着加深对jquery的理解,也想封装下简单易用的组件方便在实际项目中去调用,网上可能有更多功能更复杂的插件,但是我更多的是去学习封装插件的思想,大神勿喷。

###第一步准备jquery工具

1
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js" ></script>

###第二步先写页面结构和css样式

1
2
3
4
5
6
7
8
9
10
.mkui_loading{padding:12px 32px;background:#111;color:#fff;display:inline-block;position:fixed;
border-radius:4px;
box-shadow: 1px 1px 1em #111;
}
<body>
<div class="mkui_loading">
<span>页面正在加载中...</span>
</div>
</body>

###第三步开始写插件,因为是基于jquery开发插件,因此将插件对象绑定在jQuery对象上面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
(function($){
//组件的入口
$.mkLoading = function(options){
var opts = $.extend({},$.mkLoading.defaults,options);
//模板初始化
var $loading = $.mkLoading.template(opts);
//居中问题
$.mkLoading.position($loading);
//事件绑定
$.mkLoading.events($loading,opts);
};
//组件的模板
$.mkLoading.template = function(opts){
var $loading = $("<div class='mkui_loading animated bounceInUp'><span>"+opts.content+"</span></div>");
$("body").append($loading);
return $loading;
};
//loading的位置 fixed
$.mkLoading.position = function($loading){
var winw = $(window).width();
var winh = $(window).height();
var lw = $loading.width();
var lh = $loading.height();
var left = (winw - lw)/2;
var top = (winh - lh)/2;
$loading.css({left:left,top:top});
};
//绑定事件
$.mkLoading.events = function($loading,opts){
$(window).resize(function(){
$.mkLoading.position($loading);
});
$loading.on("click",function(){
if($loading.timer)clearTimeout($loading.timer);
//css3关键帧开发的,它不支持ie678,ie678用淡入淡出
$(this).remove("animated bounceInDown").addClass("animated bounceOutUp")[opts.animate](1000,function(){
$(this).remove();
});
});
//定时关闭
if(opts.time){
if($loading.timer)clearTimeout($loading.timer);
$loading.timer = setTimeout(function(){
$loading.trigger("click");
clearTimeout($loading.timer);
},opts.time * 800);
}
};
//默认参数的定义
$.mkLoading.defaults = {
content:"请稍后,数据加载中...",
animate:"fadeOut",
time:0
};
})(jQuery);

###这是第一个版本,第二版本会做拖拽….

End.

Share Comments