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

写了一个简单的jquery插件(初恋啊)

2014-09-24 17:04 525 查看
用了好久的jquery了,却没有写过插件,今天研究了一个别人的插件和一些文章,总算搞清楚了jquery插件一些写法,

代码写了一个div当鼠标事件发生时的宽高变化情况,基础,代码基础,基础好了,才能研究深入的东西.

(function(jQuery){
/*
*  插件应该返回一个JQuery对象,以便保证插件的可链式操作。
*  JQuery插件的机制:jQuery提供了2个用于扩展jQuery功能的方法
*  jQuery.fn.extend()
*  jQuery.extend()
*  自定义插件的样式是必不可少的 (options 就是传入的参数集合)
       *  jQuery.fn.插件名=function(){...}   这个很重要
*/

       /*
          jQuery.fn.插件名解释: fn这个其实就是 var fn = jQuery.prototype(定义了prototype原型的别名)  可以参照书籍<< 基于MVC的JavaScript Web富应用开发 >>
        */ 
    
jQuery.fn.color=function(options){
/*-----------------  这里写功能需求-----------------------*/

console.log(jQuery);

//这里给插件的属性设置一些默认的值
var defaults={
width:400,
height:400
};

//使用extend()方法重构插件的属性

var attributes=jQuery.extend(defaults,options);

/*
*
* return this.each(...)   返回通过选择器获取的jQuery对象    this.each遍历所有的元素
*
*/

function changeWidth(target){

//console.log(target);

target.animate({
width:defaults.width,
height:defaults.height
});
}

this.each(function(){

var target=jQuery(this);

var oldW=target.width();
var oldH=target.height();

//console.log(target);

target.mouseover(function(){

target.css('backgroundColor','green');
changeWidth(target);

});

$(this).mouseout(function(){

$(this).animate({
backgroundColor:'orange',
width:oldW,
height:oldH
});

});
});

};

})(jQuery);


代码调用很简单:

<script src='./jquery.min.js'></script>
<script src='./jquery.color.js'></script>
<script>
$(document).ready(function(){
$('#div').color({width:1000,height:500});
});
</script>


当有了基础,可以深入别人的代码去研究.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: