我寫了一個非常簡單的插件,它允許我使用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>')
這很好。我以爲在發佈這個問題之前我嘗試了這個,但是當我將$ .fn.css存儲在一個變量中時,它只是存儲了一個引用 - 它成爲了對覆蓋函數的引用。我用'this._css(opts)'調用,但得到錯誤。我並不完全理解'apply'發生了什麼,但它效果很好 - 謝謝你們。 –
你是一個jquery大師;) –
甚至沒有關閉,我很害怕,但感謝客氣的話。很高興你解決了你的問題。 –