最近面试,遇到求职者建立上写道熟练掌握jQuery。然后我就问了,知道怎么封装插件吗?然后就没有然后了。
写一个简单的插件,就是一个提示弹框:
(function($){
$.fn.tips =function(options){
var opts =null;
var defaults = {
text:"一个提示",
color:"#f7f7f7",
padding:"18px",
background:"#000",
cover:"rgba(0,0,0,.4)"
};
opts =$.extend({}, defaults, options);
var _obj = {
data: {
txt:opts.text,
col:opts.color,
pad:opts.padding,
bac:opts.background,
cov:opts.cover
},
_init:function(){
this.add();
this.hid();
},
add:function(){
var _inner =$("<div>");
_inner.addClass("tips-center");
$("body").append(_inner);
_inner.text(this.data.txt);
_inner.css({
"padding" :this.data.pad,
"background" :this.data.bac,
"color" :this.data.col,
"position" :"fixed",
"zIndex":"10",
"top" :"50%",
"left" :"50%",
"border-radius" :"5px",
"-webkit-transform" :"translate(-50%,-50%)",
"-moz-transform" :"translate(-50%,-50%)",
"transform" :"translate(-50%,-50%)"
});
$("html").height("100%");
$("body").height("100%");
var _back =$("<div>");
_back.addClass("tips-back");
$("body").append(_back);
_back.css({
"background" :this.data.cov,
"position" :"fixed",
"zIndex":"9",
"height":"100%",
"width":"100%",
"top":"0",
"left":"0"
});
},
hid:function(){
if($(".tips-back")&&$(".tips-center")){
$(".tips-back").click(function(){
$(".tips-center").remove();
$(".tips-back").remove();
})
}
}
}
return function(){
_obj._init();
}();
};
})(jQuery);
使用:
$("body").tips({
text:"only you"
});
简单聊一聊插件封装的原理:
只有对于jQuery的插件封装有两种方式:一种是$.fn.xxx=function(){],另一种是$.fn.extend({xxx})。
只有一点你要注意的就是,在插件的范围内,this代表将要执行的插件内容的DOM对象。
一般,都会将你要写的插件包含在一个封闭程序中,防止发生冲突,也为了防止$被覆盖掉:
;(function($){
$.fn.xxx = function (){
// 执行的插件代码
}
})(jQuery);