从今年第一天上班开始,一直在学习jquery插件方面的知识,到现在也快有两个星期了,感觉学好这插件不难。因为想学好它,所以一直都很努力!
总结jquery插件书写格式为(如有错误,欢迎指正!):
(function($){ //扩展这个方法到jquery; $.fn.extend({ //将可选择的变量传递给方法如:slideimg slideimg: function(options) { //参数和默认值 var defaults = { //默认内容区 }; var options = $.extend(defaults, options); //遍历匹配元素的集合 return this.each(function() { //执行内容区: }); } }); })(jQuery);
(function($){ //扩展这个方法到jquery; $.fn.extend({ //将可选择的变量传递给方法 slideimg: function(options) { //参数和默认值 var defaults = { tol_class:'.goleftbtn', //获得点击左按钮的class tor_class:'.gorightbtn', //获得点击右按钮的class slide_class:'.slide_tolr', //获得滑动层的class center_class:'.star', //获得中间点的class imgshow_num:'3', //最多可见图片的张数; cen_dot_bar:'ture', //当cen_dot_bar为'ture'时中间显示,否则关闭; gostart_on:'ture', //自动运行开关 dotimg_src:'../images/slideimg/cir.gif', //中间点src centerbar_class:'.center_dot', //中间点所在层的class runtime:'2000' //自动运行时间 }; options = $.extend(defaults, options); var count = 1; var checkname; //遍历匹配元素的集合 return this.each(function() { var o =options; //获得最外层的ID; var thisid = $(this).attr("id"); //转化:去除中间点的class的’.‘ var cenclass =o.center_class.substr('1'); //获得中间点击点处的class var centerBar = $($(this).find(o.centerbar_class),$(this)); var slidebar = $($(this).find(o.slide_class),$(this)); //最多滑动的次数(Math.ceil()方法向上取整) o.maxnum = Math.ceil(slidebar.children().prev().size()/o.imgshow_num); //设置可见层的宽 o.slide_wid = slidebar.parent().width(); //设置滑动层的宽; slidebar.css("width",o.slide_wid*o.maxnum+"px"); //添加中间处的点击点 if(o.cen_dot_bar === 'ture'){ for( i=1;i<=o.maxnum;i++){ $(centerBar).append( "<span" + ' ' + "name="+i+ " " +"class="+"'"+cenclass+' '+cenclass+i +"'" + ">"+"<img src="+ o.dotimg_src +" />"+"</span>" ); } } var goleftbtn = $($(this).find(o.tol_class),$(this)); var gorightbtn = $($(this).find(o.tor_class),$(this)); var clickCenter = $($(this).find(o.center_class),$(this)); //点击向左按钮时; $(goleftbtn).click(function(){ if(count > 1){ count--; com_cen_src(); }else{ count = o.maxnum; com_cen_src(); } }); //点击向右按钮时; $(gorightbtn).click(function(){ if( count < o.maxnum){ count++; com_cen_src(); }else{ slidebar.animate({left:'0'},{queue:false}); count = 1; com_cen_src(); } }); //点击中间点时 $(clickCenter).click(function(){ checkname = $(this).attr("name"); count = checkname; com_cen_src(); }); //调置中间点击处的透明度 $(o.center_class+" img").css({"opacity":"0.3","cursor":"pointer"}); $(o.center_class+"1"+" img").css("opacity","0.95"); $(o.tol_class+" img" +","+o.tor_class+" img").css("opacity","0.3"); $(o.tol_class+" img" +","+o.tor_class+" img").hover(function(){ $(this).css("opacity","1"); },function(){ $(this).css("opacity","0.4"); }); function com_cen_src(){ slidebar.animate({left:'-' + o.slide_wid*(count-1)},{queue:false}); $("#"+ thisid +" "+o.center_class+" img").css("opacity","0.3"); $("#"+ thisid +" "+o.center_class + count + " img").css("opacity","0.95"); } }); } }); })(jQuery);