您的位置:首页 > Web前端 > JQuery

jquery plugin 插件写法入门

2011-01-28 16:00 330 查看
不多说了,看代码,你懂的。

/*
*** 重设指定图片的大小
*/
(function($){
$.fn.extend({
   //将可选择的变量传递给方法
resize: function(options) {
//设置默认值并用逗号隔开
var defaults = {
maxWidth : 200,
maxHeight : 100
}
var options =  $.extend(defaults, options);
return this.each(function() {
var o = options;
objImgs = $(this).find("img");
for( i =0;i<objImgs.length;i++)    {
destObj = $(objImgs[i]);
//注意,简单的直接的易懂的代码才是好代码,确实有精简的很艺术化的代码,但不要轻易使用。
oldWidth = destObj.attr("width");
oldHeight= destObj.attr("height");
rate =  oldWidth/oldHeight;
 if(destObj.attr("width") > o.maxWidth) { //如果宽超限,重置宽
destObj.css("width",o.maxWidth+"px");
destHeight = o.maxWidth/rate;
destObj.css("height",destHeight+"px");
}
oldHeight= destObj.attr("height");
if(oldHeight > o.maxHeight)  {
destObj.css("height",o.maxHeight+"px");
destWidth = o.maxHeight*rate;
destObj.css("width",destWidth+"px");
}
}
});
}
});
})(jQuery);

//推送至微博.

(function($){
$.fn.extend({
   //将可选择的变量传递给方法
push2tb: function(options) {
//设置默认值并用逗号隔开
var defaults = {
_t : encodeURI(document.title),
_url : encodeURIComponent(document.location),
_appkey : encodeURI("appkey"),
_site :'5y173游戏网'
}
var options =  $.extend(defaults, options);
return this.each(function() {
var o = options;
objImgs = $(this).find("img");
for( i =0;i<objImgs.length;i++)    {
destObj = $(objImgs[i]);
destObj.attr("title","双击即可转发至qq微博,与好友分享!");
destObj.css("cursor","pointer");
_pic = objImgs[i].src;  //用这个,可以带http 方便预览
_pic = encodeURI(_pic);
destObj.dblclick(function (){
_u = 'http://v.t.qq.com/share/share.php?title='+o._t+'&url='+o._url+'&appkey='+o._appkey+'&site='+o._site+'&pic='+_pic;
window.open( _u,'转播到腾讯微博', 'width=700, height=680, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, location=yes, resizable=no, status=no' );
});
}
});
}
});
})(jQuery);


两个功能,一个按比例缩放图片,一个将图片推送至微博,刚开始写jquery plugin 手还比较生,继续努力。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: