zoukankan      html  css  js  c++  java
  • 写了一个简单的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 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 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 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({1000,height:500});
        });
    </script>

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

  • 相关阅读:
    计算一个未排序数组中排序后相邻元素的最大差值
    13 类对象的声明中加小括号{}和不加小括号{}的区别
    12 表中删除重复项
    11 常量区的内容不能被修改
    10 无向图的边
    顺时针旋转矩阵
    字符串的旋转
    动态规划算法
    贪心算法应用-最小生成树
    贪心算法应用-单元最短路径
  • 原文地址:https://www.cnblogs.com/hellome/p/3991127.html
Copyright © 2011-2022 走看看