Jquery.fn.css Gets the property value "$ (...) of the first element in the element that matches the current jquery." CSS (cssname), note that this cssname can be an array "or set the style value" $ (...) for each element that the current jquery matches. CSS (Cssname,value)/$ (...). CSS (obj) "; The
can see that the function is called directly inside the jquery.access to handle. Access breaks down elements that match the jquery object of the current multiple elements into a single element called the callback function (Elem, name, value) in the second argument, and if the argument name is an object, Access internal decomposition name recursive calls each of the Key/value key values for name
source
Jquery.fn.css: function ( name, value ) { // Access decomposes the current jquery object into a single element to invoke the callback function ( elem, name, value ) in the second argument, //If the argument name is an object, access internal decomposition name recursive call processes each of the name's key/value key value pairs return Jquery.access ( this, function ( elem, name, value ) { var len, styles, map
= {}, i = 0; //if the CSS feature name is an array, such as [' Left ', ' marginright '] if ( jquery.isarray ( name ) ) {
styles = getstyles ( elem ); len =&nbSp;name.length; //$.css () to obtain the corresponding CSS feature value for ( ; i < len; i++ ) { map[ name[ i ] ] = jquery.css ( elem, name[ i ],
false, styles ); }
return map; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} //value A value then call $ . Style sets a single CSS value, and the value parameter has no value, and the corresponding CSS eigenvalue is obtained by $.CSS () return value
!== undefined ? jquery.style ( elem, name, value ) : jquery.css ( elem, name );
}, name, value, arguments.length > 1 ); }
This API is relatively simple, but careful analysis of the functions called inside will find a lot of knowledge. Behind Yi Yilai excavation.
First we see the function of Getstyles (elem) and look at his definition
if (window.getComputedStyle) {
getstyles = function (elem) {return
window.getComputedStyle (Elem, NULL);
};
...
ie8-compatible
} else if (Document.documentElement.currentStyle) {
getstyles = function (elem) {
Retu RN Elem.currentstyle;
};
...
}
Two different methods window.getComputedStyle and Elem.currentstyle. Then analyze them all.
A. window.getComputedStyle
Complete expression window.getComputedStyle (Elem,pseudo)
Elem:dom node, you must
Pseudo: Pseudo class, and only pseudo-element pseudo class, such as: After,::before,::first-letter,::first-line. The second argument "pseudo class" is required before the optional "Gecko 2.0 (Firefox 4/thunderbird 3.3/seamonkey 2.1)"
Description: This function is taken out of the CSS after the final use of the CSS property value "which does not include positional relationships Left/right/top/bottom attribute values, such as left:10%, then through the getComputedStyle get left or" 10% "(Safari 5.1.7 's margin-right returns a percentage, which requires special handling). Read-only. Good support in modern browsers, no support for ie8-
Examples (This example will go through the full text):
<style>
#myList {
height:100px;
}
#myList: after{
Content: ' A ';
height:100px;
}
</style>
<ul id= "myList" style= ' width:50%;left:666px; ><li>test</li></ul>
<ul id= "MyList2" style= ' width:50%;left:111px; ><li>test2</li></ul>
The getComputedStyle value is the computed value (for example, the percentages are converted to pixels), and the following example
The width 50% is converted to pixels.
The second argument in getComputedStyle is only a pseudo-element artifact that works, as in the following instance
As the above figure shows, as long as the following pseudo element does not or does not pass the pseudo element pseudo class This parameter, then obtains is also the first parameter corresponding element's getComputedStyle value. The left and. Content properties can testify in the image above.
getComputedStyle gets a read-only group object, each element of the array is a CSS style name, and the read-only group object has a property that corresponds to one by one of each element in the array to hold the value of the CSS style. Let's look at the structure first (window.getComputedStyle (document.getElementById (' myList '), NULL)
But because we don't support ie8-, we need a way that IE8 can support. This is IE's own dongdong Elem.currentstyle
B. Elem.currentstyle
Elem.currentstyle is also a read-only object.
The difference between Elem.currentstyle and getComputedStyle
1. Elem.currentstyle is a pure object in ie8-, without the structure of the class array, the CSS style name cannot be obtained by style[n], and Elem.currentstyle is a class array object in ie9+.
2. The style obtained by Elem.currentstyle is a final CSS style, but not a calculated style, such as the previous example
getComputedStyle's width results in pixel value 632px
And the result of the Elem.currentstyle is that the percentage value set is 50%
3. Differences in style names, such as for float properties, ie8-Currentstyle is stylefloat
And Firefox getComputedStyle is cssfloat and float "recommended not to use, browser retention, but also non-standard methods, browsers can not support" coexist
In Chrome, getComputedStyle is shown as float, which is actually not recommended for use by float, browser retention, and non-standard methods, browsers are not supported and cssfloat can be obtained
And IE9 are both Cssfloat and stylefloat.
So the way jQuery gets the float property is "float": jQuery.support.cssFloat? "Cssfloat": "Stylefloat"
C. elem.style
Elem.style and window.getComputedStyle (Elem,pseudo) and Elem.currentstyle comparisons
Elem.style is the inline style that gets the elem. This is one of the different places than window.getComputedStyle (Elem,pseudo) and Elem.currentstyle.
Style results are readable and writable, while getComputedStyle and currentstyle results are read-only.
The style result is a result of no calculation, similar to Currentstyle, getComputedStyle is the computed result. The Style.width value in the following figure is 50%, not the pixel value
D. Modern browsers gets the value of a style in a style sheet--getpropertyvalue
GetPropertyValue (ClassName) is a modern browser (Ie9+,firefox,chrome ...) A property method for a style sheet. So as long as it's a modern browser, the style sheet style obtained above Getcomputedstyle/currentstyle/style three ways can use this method to get the style value. such as Style.getpropertyvalue ("float").
Note that classname is a direct attribute name (such as "Background-color"). is "float" rather than "css-float" or "cssfloat".
If you obtain a float value by using property capture, you need to convert to "cssfloat" or "stylefloat", such as
This is a bit of a toss.
And since ie8-does not support this method, ie8-directly uses the property acquisition method
Ie8-'s currentstyle also supports another way to get a property: Style.getattribute (ClassName).
It should be noted that the classname can be either a direct attribute name or a hump (such as "Background-color" or "BackgroundColor").
So, we have two ways of dealing with styles for compatibility
1. Combined with GetPropertyValue (ClassName) and GetAttribute (ClassName), because both className can be direct property names
2. Using the property capture method Style[classname] But note that property names need to be compatible, for example: "Float" needs to be replaced by "cssfloat" or "stylefloat".
and jquery's processing is to choose the second way.
Here, though jquery uses the second approach, there is a property that uses property to get it to fail, which is the "filter" attribute of the wonderful work. This property must use GetPropertyValue to get the correct
Use the table to summarize the relative usage of CSS property acquisition
Characteristics |
getComputedStyle |
Currentstyle |
Style |
Browser support situation |
Ie9+,chrome,firefox ... |
Ie |
All |
Readable to write |
Read-only |
Read-only |
Readable to write |
Whether to calculate the final value (for example, percentages, proportions are calculated as real pixel values) |
Is |
Whether |
Whether |
(External style sheet + internal style sheet + inline style) end result |
Is |
Is |
No (inline style only) |
Property capture Methods Style.name and Style[name] |
Support (Except for "Filter" property) |
Support |
Support |
Supported methods for obtaining CSS property values |
GetPropertyValue |
Ie8-supports only getattribute;ie9+ support GetPropertyValue and GetAttribute ("filter") |
Ie8-supports only getattribute;ie9+ support GetPropertyValue and GetAttribute ("filter"); Other browsers only support GetPropertyValue |
Outstanding Advantages |
Standardize and support pseudo elements (e.g.: after) to obtain computed results |
|
Readable to write |
|
|
|
|
Then continue to analyze the source code:
Now that you know the various ways to get a CSS style sheet, next look at a calculated merit function Curcss = functions (Elem, Name, _computed) corresponding to the specified CSS style name. The difficulty is that the value obtained through Currentstyle and getComputedStyle may be a percentage or a relatively worthwhile time, and we need to simulate and compute the real value. Process comparison point list, see Source code annotation
Note: We included "window" in window.getComputedStyle//Because node.js in js dom would be terminated without him if ( window.getcomputedstyle ) { getstyles = function ( elem ) { return window.getcomputedstyle ( elem,
null );
}; Curcss = function ( elem, name, _computed ) {var width, minwidth, maxwidth, computed = _computed | | getstyles ( elem ),// getpropertyvalue only used ret = in IE9 .css (' filter ') Computed ? computed.getpropertyvalue ( name ) | |
computed[ name ] : undefined, style = elem.style; if ( computed ) {if ( ret === "" && !jquery.contains ( elem.ownerDocument, elem ) ) {ret&Nbsp;= jquery.style ( elem, name ); // chrome < 17 and safari 5.0 calculates margin-right// safari using "calculated results" instead of "used values"
5.1.7 (latest) percent return but we need pixel values, which violate the Cssom draft//http://dev.w3.org/csswg/cssom/#resolved-values//simulation calculation if ( rnumnonpx.test ( ret ) && rmargin.test ( name ) )
{//Save the original value width = style.width;
minwidth = style.minwidth;
maxwidth = style.maxwidth; Add a new value to get the calculated value, such as when MarginRight is 10%, by putting a width of 10%, and then through the computed.width can get 10% corresponding px width style.minwidth =
style.maxwidth = style.width = ret;
ret = computed.width;
Restore the changed value style.width = width;
style.minwidth = minwidth;
style.maxwidth = maxwidth;
}} return ret;
}; Low version IE compatible} else if . ( document.documentElement.currentStyle ) { getStyles = function ( elem ) { return elem.currentstyle
;
}; curcss = function ( elem, name, _computed ) { var left, rs, rsleft, computed = _computed | | getstyles ( elem ), ret = computed ? computed[ name ] : undefined,
style = elem.style; //here avoid setting null characters for RET //so we don't default to "Auto" if ( ret == null && style && style[ name ] ) {
ret = style[ name ]; } // we're going to convert him to pixels in a weird ending number (like 1em) // but not positional properties, they should be proportional to the parent element, and we can't measure the proportions of the parent element, because he could be a stack of scales (like <div style= ' left:10% ' >
<p style= ' left:20% ' ><span style= ' left:20% ' ></span></p></div>), could not be calculated at all if ( rnumnonpx.test ( ret ) && !rposition.test ( name ) ) { //Save the original value left =
style.left; rs = elem.runtimestyle; rsLeft = rs &&
rs.left; //add a new value to get calculated value if ( rsLeft ) { rs.left =
Elem.currentStyle.left; } style.left = name === "FontSize" ? "1em"
: ret; ret = style.pixelleft +
"PX"; //restore the changed value style.left = left;
if ( rsLeft ) { rs.left =
rsLeft; } &NBSP;&NBSP} return ret === " ? "
Auto " : ret;
}; }
According to the last processing of the JQUERY.FN.CSS function
return value!== undefined?
Jquery.style (elem, Name, value):
jquery.css (elem, name);
You know the two key low-level api:jQuery.style and jquery.css that CSS handles. The
has previously analyzed that only. Style is readable, and, similarly, the Jquery.style function is also used to read and write inline styles. The processing process for the Jquery.style is
1. Fixed CSS feature name saved as OrigName, the name that really can be recognized by the browser is saved as named.
2. Find csshooks for name or OrigName.
3. If the value is set (there is a pass value parameter), set it. The more special processing is that value can be a cumulative string (such as: "+ +") first by jquery.css the original value to be computed. If value is a number, you need to see if the PX unit is added depending on the situation. If there is a corresponding csshooks also need special treatment and so on.
4. If you are getting a value (without passing the value parameter), there are two situations in which a hooks is obtained by hooks or directly style[name].
Source
Sets or gets a style eigenvalue for a DOM node jquery.style: function ( elem, name, value, extra ) { //text and annotation nodes cannot set style feature values if ( !elem | | elem.nodetype === 3 | | elem.nodetype === 8 | | !elem.style ) { return; //modifies the CSS feature name to fit the current browser var ret, type, hooks origname = jquery.camelcase ( name ),
style = elem.style; //jquery.cssprops cache queried CSS feature name for subsequent easy to find use name = jquery.cssprops[ origname ] | | ( jquery.cssprops[ origname ] = vendorpropname style, origName
) ); //gets a prefix version of the hooks orNo prefix version of hooks hooks = jquery.csshooks[ name ] | |
jQuery.cssHooks[ origName ]; //If you are setting a value for a CSS feature name if value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 //
Rrelnum = new regexp ( "^ ([+-]) = (" + core_pnum + ")", "I" " //converts the relative number of strings +=/-= to the corresponding number if ( type === "string" && (Ret = rrelnum.exec ( value )) ) { //(+ + 1) == 1; (- + 1) == -1 value = ( ret[1] + 1 ) * ret[2]
+ parsefloat ( jquery.css ( elem, name ) );
// Fixes bug #9237
type = "Number";
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} //nan and Null are not available if ( value == null | | type === "Number" && isnan ( value ) ) {
return; } // Except for CSS features that are not set to pixel units, the rest is addedPlus "px" if ( type === "number" & & !jQuery.cssNumber[ origName ] ) {
value += "px"; } //
support.clearclonestyle = div.style.backgroundclip === "Content-box"; //div.style.backgroundclip is not "Content-box" mode and The value set by //is empty background ... Set it to inherit the parent node style // Fixes #8908, It is more accurate to set the default value for each problem feature, but it will call at least 8 times function if ( ! jquery.support.clearclonestyle && value === "" && name.indexof (" Background ") === 0 ) {&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp; style[ name ] = "Inherit"; } // If the hook is provided, set the value with the hook, otherwise set the top value if ( !hooks | | ! ("Set" in hooks) | | (Value = hooks.set ( elem, value, extra )) !== undefined ) { //When the value you want to set is an invalid value ie throws an exception // Fixes bug #5509 try {
style[ name ] = value; } catch (e) {} &nBSP;&NBSP;&NBSP} //Get value } else { //If a hook is provided, use the hook to take the value if ( hooks && "Get" in hooks && (Ret = hooks.get ( elem, false, extra )) !== undefined ) {
return ret; } //
Other cases take value from the Style object return style[ name ]; &NBSP;&NBSP;&NBSP;&NBSP}//Returns a CSS feature name, which may be a feature name function vendorpropname that the vendor has added a prefix ( style, name ) { //short name not added vendor prefix if ( name in style ) {return name; } //Check the vendor prefix name
//cssPrefixes = [ "Webkit", "O", "Moz", "MS" &NBSP;]
var capname = name.charat (0). toUpperCase () + name.slice (1), origname = name,
i = cssPrefixes.length; while ( i-- ) {
name = cssprefixes[ i ] + capname; if ( name in style ) {return
name; } return origName; }
jquery.css processing is also relatively simple
1. Fixed CSS feature name saved as OrigName, the name that really can be recognized by the browser is saved as "
2". If a corresponding csshooks is present, otherwise the Curcss method is used to get the style value
3. The default value for the acquired style value is to be handled, for example, the value of the CSS style fontweight default is "normal" corresponding to 400.
Source
Get the CSS eigenvalue corresponding to name Css: function ( elem, name, extra, styles ) { var num, val, hooks, origname = jquery.camelcase (
name ); //fixed name name = jquery.cssprops[ origname ] | | ( jquery.cssprops[ origname ] = vendorpropname ( elem.style, origname
) ); //gets a prefix version of the hooks or a hooks with no prefix version hooks = jquery.csshooks[ name ] | |
jQuery.cssHooks[ origName ]; //extract value from Hook if ( hooks && "Get" in hooks ) { val = hooks.get (
elem, true, extra ); &NBSP;&NBSP;&NBSP;&NBSP} //other cases using CURCSS value &NBSP;&NBSP;&Nbsp; if ( val === undefined ) {
val = curcss ( elem, name, styles ); } //cssnormaltransform = {letterspacing: 0, fontweight: 400} //converts "normal" to calculated value if ( val === "Normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ]; &NBSP;&NBSP;&NBSP;&NBSP} //forces or provides a qualifier and Val looks like a number to force into a number and returns &NBSP;&NBSP;&NBSP;&NBSP;IF ( extra === "" | | extra ) { num = parsefloat ( val
); return extra === true | | jquery.isnumeric ( num ) ? num | |
0 : val;
} return val; }