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

用了好久的jquery了,却没有写过插件,今天研究了一个别人的插件和一些文章,总算搞清楚了jquery插件一些写法,

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

 1 (function(jQuery){
 2         /*
 3          *  插件应该返回一个JQuery对象,以便保证插件的可链式操作。 
 4          *  JQuery插件的机制:jQuery提供了2个用于扩展jQuery功能的方法
 5          *  jQuery.fn.extend()
 6          *  jQuery.extend()
 7          *  自定义插件的样式是必不可少的 (options 就是传入的参数集合)
       * jQuery.fn.插件名=function(){...} 这个很重要
8 */ 9
       /*
          jQuery.fn.插件名解释: fn这个其实就是 var fn = jQuery.prototype(定义了prototype原型的别名) 可以参照书籍<< 基于MVC的JavaScript Web富应用开发 >>
        */ 
     10 jQuery.fn.color=function(options){ 11 /*----------------- 这里写功能需求-----------------------*/ 12 13 console.log(jQuery); 14 15 16 //这里给插件的属性设置一些默认的值 17 var defaults={ 18 width:400, 19 height:400 20 }; 21 22 //使用extend()方法重构插件的属性 23 24 var attributes=jQuery.extend(defaults,options); 25 26 /* 27 * 28 * return this.each(...) 返回通过选择器获取的jQuery对象 this.each遍历所有的元素 29 * 30 */ 31 32 function changeWidth(target){ 33 34 //console.log(target); 35 36 target.animate({ 37 width:defaults.width, 38 height:defaults.height 39 }); 40 } 41 42 43 44 this.each(function(){ 45 46 var target=jQuery(this); 47 48 var oldW=target.width(); 49 var oldH=target.height(); 50 51 //console.log(target); 52 53 target.mouseover(function(){ 54 55 target.css('backgroundColor','green'); 56 changeWidth(target); 57 58 }); 59 60 $(this).mouseout(function(){ 61 62 $(this).animate({ 63 backgroundColor:'orange', 64 width:oldW, 65 height:oldH 66 }); 67 68 }); 69 }); 70 71 72 73 }; 74 75 76 })(jQuery);

代码调用很简单:

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

当有了基础,可以深入别人的代码去研究.

 

转载于:https://www.cnblogs.com/hellome/p/3991127.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值