標籤:style blog color io 使用 ar div sp cti
用了好久的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 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.height39 });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:oldH66 });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>
當有了基礎,可以深入別人的代碼去研究.
寫了一個簡單的jquery外掛程式(初戀啊)