2011-09-16 72 views
8

我寫了一個非常簡單的插件,它允許我使用0xffccaa格式的css顏色代替'#ffccaa'(主要是爲了避免寫引號 - 還允許通過簡單地添加到它作爲一個整數)。如何從插件擴展jQuery.css

我正在按$().xcss({})執行,但寧願只使用$().css({})

如何擴展$.fn.css函數的功能,並且我需要注意哪些缺陷?

另外,我想我會想要做同樣的$.animate

小提琴:http://jsfiddle.net/hB4R8/

// pugin wrapper 
(function($){ $.fn.xcss = function(opts){ 
    // loop through css color properties 
    $.each(['background', 'backgroundColor','background-color', 'color', 'borderColor','border-color'],function(i,v){ 
     // if set as number (will be integer - not hex at this point) 
     // convert the value to `#ffccaa` format (adds padding if needed) 
     if(typeof opts[v] === 'number') 
      opts[v] = ('00000'+opts[v].toString(16)).replace(/.*([a-f\d]{6})$/,'#$1') 
    }) 
    // run css funciton with modified options 
    this.css(opts) 
    // allow chaining 
    return this 
} })(jQuery) 

// test the plugin 
$('body').xcss({ 
    'background-color': 0xffccFF, 
    color: 0xccffcc, 
    border: '3px solid red', 
    borderColor:0x0ccaa, 
    padding:50 
}).html('<h1>This should be a funny color</h1>') 

回答

5

這似乎爲我工作:http://jsfiddle.net/frfdj/

(function($) { 
    var _css = $.fn.css; // store method being overridden 
    $.fn.css = function(opts) { 
     $.each(['background', 'backgroundColor', 'background-color', 'color', 'borderColor', 'border-color'], function(i, v) { 
      if (typeof opts[v] === 'number') opts[v] = ('00000' + opts[v].toString(16)).replace(/.*([a-f\d]{6})$/, '#$1') 
     }) 
     return _css.apply(this, [opts]); // call original method 
    } 
})(jQuery) 
+0

這很好。我以爲在發佈這個問題之前我嘗試了這個,但是當我將$ .fn.css存儲在一個變量中時,它只是存儲了一個引用 - 它成爲了對覆蓋函數的引用。我用'this._css(opts)'調用,但得到錯誤。我並不完全理解'apply'發生了什麼,但它效果很好 - 謝謝你們。 –

+0

你是一個jquery大師;) –

+0

甚至沒有關閉,我很害怕,但感謝客氣的話。很高興你解決了你的問題。 –

2

https://github.com/aheckmann/jquery.hook/blob/master/jquery.hook.js

基於此代碼用於創建任意函數的鉤子,你可以重寫$ .fn.css與你想要做什麼調用之前的方法原創功能。

+0

一個非常有趣的答案/功能。對我來說有兩個問題:1.是否需要使用選擇器,因此我使用'*'來選擇頁面上所有效率低下但更重要的對象2.它僅對頁面上已有的元素進行操作,而不是之後動態創建的元素。這裏是我用來讓它適用於這些限制的代碼的鏈接:[gist](https://gist.github.com/1222547)。感謝您提供一個有趣的鏈接和一個有趣的答案。 –