The css()
jQuery method requires two steps: first jQuery defines some filters to be applied to the CSS properties, then specifies the actual method:
var rexclude = /z-?index|font-?weight|opacity|zoom|line-?height/i, ralpha = /alpha\([^)]*\)/, ropacity = /opacity=([^)]*)/, rfloat = /float/i, rdashAlpha = /-([a-z])/ig, rupper = /([A-Z])/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, cssShow = { position: "absolute", visibility: "hidden", display:"block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], // cache check for defaultView.getComputedStyle getComputedStyle = document.defaultView && document.defaultView.getComputedStyle, // normalize float css property styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat", fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn.css = function( name, value ) { return access( this, name, value, true, function( elem, name, value ) { if ( value === undefined ) { return jQuery.curCSS( elem, name ); } if ( typeof value === "number" && !rexclude.test(name) ) { value += "px"; } jQuery.style( elem, name, value ); }); };
Filters are used to exclude the CSS properties in order to add pixels to the style definitions. Then jQuery checks if the W3C DOM method getComputedStyle()
is supported or not and if the browser in question supports the CSS float
property as cssFloat
or styleFloat
. The actual css()
method performs two tasks:
- if the style value passed in is
undefined
, returns the computed style of the current element for the specified property - if a property can accept pixels as its values and if
px
has not been specified (ie. the value passed in is a number), it addspx
to the CSS value - applies the specified styles to the current element.