Author: nuysoft/high cloud QQ: 47214707 Email: nuysoft@gmail.com
Disclaimer: This article is an original article. If you need to reprint it, please indicate the source and retain the original article link.
Jquery source code analysis series (Continuous updates)
Style Sheet
Overview
How to Use
Usage Details
Implementation Principles of features
Source code analysis
. CSS (name, value)
Jquery. style (ELEM, name, value, extra)
Jquery.css (ELEM, name, extra)
Curcss (ELEM, name)
Overview
Source code analysis of CSS operations is based on version1.7.1In the future, the jquery source code analysis series will adopt the latest version.
Jquery.fn.css () mainly solves three problems:
Browser compatibility: IE, W3C
Compatible with HTML style attributes and Dom style attributes: Hyphen, camper
Makes setting style attributes of elements quick and easy: Unified interface for detecting, setting, and reading dynamic parameters
How to Use
Jquery.fn.css () hasThe first method is to read the style property value, and the other three are to set the style property value.:
. CSS (propertyname) gets the style attribute value of the first element. propertyname is the CSS attribute name.
. CSS (propertyname, value) sets a CSS attribute on the matched element set. value is the attribute value to be set.
. CSS (propertyname, function (index, value) sets the function return value as the property value.
Function (index, value) returns the attribute value to be set. The context of the function this points to the current element and receives two parameters: Index is the subscript position of the current element in the Set; value is the old value, that is, the current value (meaning that the current value must be retrieved before setting)
. CSS (MAP) to set multiple styles
Map contains a map of key-value pairs. The key is the attribute name, and the value is a literal volume or function.
Usage Details
What are the difficulties in reading and setting style sheets?Browser compatibility. For exampleThe method for accessing style attributes is different.:
// Var defaultview = ELEM & ELEM in a standard-based browser. ownerdocument. defaultview; var computedstyle = defaultview & defaultview. getcomputedstyle (ELEM, null); var ret = computedstyle & computedstyle. getpropertyvalue (name); return ret; // var ret = ELEM in IE. currentstyle & ELEM. currentstyle [name] return ret;
Another common compatibility problem is that,Some attributes use different attribute names in different browsersFor example, float, stylefloat is used in the DOM Implementation of IE, and cssfloat is used in browsers that comply with W3C standards.
The. CSS () method of jqueryencapsulates these differences and returns the same results regardless of the attribute name used. For example, if an element is floating to the left, the following three lines of code return the string left in each line:
$('div.left').css('float');$('div.left').css('cssFloat');$('div.left').css('styleFloat');
If you encounterAttributes composed of multiple words. These attributes have different formats in CSS and Dom., Jquery can also be equivalent, for example:
.css( { 'background-color': '#ffe', 'border-left': '5px solid #ccc' } ).css( { backgroundColor: '#ffe', borderLeft: '5px solid #ccc' } )
Jquery can recognize and return the correct value. Note thatThe Dom attribute quotation marks are optional., AndThe CSS attribute must contain quotation marks because the attribute name contains a hyphen-.
When you use .css () to set a style,Jquery changes the style property of an element.For example, the following two lines of code are equivalent:
$('#mydiv').css('color', 'green')document.getElementById('mydiv').style.color = 'green'
Set an empty string for style PropertiesFor example, ('your mydiv'hangzhou.css ('color', ''). If this attribute is operated by the HTML style inline () method, you can directly operate the DOM style attribute style (DOM style property ); however, if it is defined in the external style sheet stylesheet or the internal style sheet <style> element, it will not be removed (jquery implementation will not modify the external style sheet and the internal style sheet, this is not as written in some books, although the browser provides native API support ).
If you encounterCSS colorDifferent browsers may return logically identical but literally different color values. There are four formats in total: # fff, # ffffff, RGB (255,255,255), and blue.
But .css ()CSS attribute abbreviations are not supportedFor example, margin background border. For example, if you want to obtain the outer distance, use the values (elemate.css ('margintop') and values (elemate.css ('marginright'), and so on.
Starting from jquery1.6, .css () canSupported relative values, Like. animate (). The relative value is a string starting with + = or-=, indicating that the current value is increased or decreased. For example, the padding-leftof a element is 10px,.css ("padding-left", "+ = 15") to change padding-left to 25px.
Starting from jquery1.4,.css ()Allows the input of a function as the attribute value.For example, in the following example, set the width of the matching element to an increasing value (increasing ):
$('elem.example').css('width', function(index) { return index * 50;});
Note: If the function does not return any value (for example, function (index, style) {}), orUndefined is returned. The current value is not changed.. This is useful if you want to selectively set the attribute value when certain conditions are met (the function does not return a value or returns undefined, with the returned null string, with different processing logic and results ).
LastAdd CSSBasic knowledgeFor more information, see http://wenku.baidu.com/view/d9a18f7e27284b73f2425089.html:
1. CSS style sheets can be written in line style, document internal style, and document external style.
2.Style priority: Intra-row style> internal style> external style, Id selector> class selector
Replace the aboveImplementation Principles of featuresBriefly elaborate (the source code analysis will be explained in detail later ):
Both configuration and reading are passed. CSS ()
Call the multi-function tool function jquery. Access (For details, refer to 03. Construct the jquery object-tool function)
Different methods are used to access style attributes.
When jquery loads and executes the code, it checks the browser features and unified getcomputedstyle or currentstyle into the jquery internal method curcss ()
Some attributes use different attribute names in different browsers
The proing between attribute names is defined in jquery.css props.
Style attributes composed of multiple words have different formats in CSS and Dom.
Use jquery. camelcase () to convert the form of the hyphen to the camelcase format.
Relative Value
Use jquery's internal regular rrelnum =/^ ([\-+]) = ([\-+. \ de] +)/to detect and extract operators and relative values, and then calculate
Function return value as attribute value
Call the multi-function tool function jquery. Access to execute the function, and pass the returned value to jquery. style.
Source code analysis
. CSS (name, value)
Jquery.fn.css = function (name, value) {// setting 'undefined' is a no-op // two parameters. If the value is undefined, no operation is performed, returns This // that is, if a style attribute is set to undefined, no operation is performed if (arguments. length = 2 & value = undefined) {return this;} // access: function (elems, key, value, exec, FN, pass) {// call the function jquery. access, traverse this, and execute the return jquery function in the parameter. access (this, name, value, true, function (ELEM, name, value) {return Val Ue! = Undefined? Jquery. style (ELEM, name, value): // set the value. The packet valueis an empty string jquery.css (ELEM, name); // value });};
. CSS () depends on three methods:
Jquery. Access () supports. CSS (),. ATTR (),. Prop (). For details, refer to 03.
Jquery. style () reads or sets the style property on the DOM Node)
Jquery.css () reads Dom style values on DOM elements
Start the analysis of jquery.style()and jquery.css ().
Jquery. style (ELEM, name, value, extra)
Jquery. style ()Read or set the style property on the DOM Node(Only the setting function of jquery.style(what is the difference between the reading function and jquery.css? Further research is required !).
This method has roughly done the following::
1. Filter text and comment, filter elements without style, and return undefined
2. convert to the camper type and correct the attribute name
3. For settings:
If it is number, filter Nan; filter NULL; if it is a relative value string, calculate
Add suffix
If a hook exists, call the set of the hook. If no hook exists, set style [name] = value;
4. Read:
If a hook exists, the get of the hook is called. If no hook exists, the style [name] is returned.
LookSource code comments:
// Get and set the style property on a DOM node // read or set the style property style propertystyle: function (ELEM, name, value, extra) on the DOM Node) {// don't set styles on text and comment nodes // filter text and comment. If there is no style attribute, if (! ELEM | ELEM. nodetype = 3 | ELEM. nodetype = 8 |! ELEM. style) {return; // undefined} // make sure that we're working with the right name // make sure the correct name var ret, type, origname = jquery is used. camelcase (name), style = ELEM. style, hooks = jquery.css hooks [origname]; // convert it to the camper format // correct the attribute name, whether to use different property names = jquery.css props [origname] in different browsers | origname; // css hook // check if we're re setting a value // set if (value! = Undefined) {type = typeof value; // convert relative number strings (+ = or-=) to relative numbers. #7345 // calculate the relative value rrelnum =/^ ([\-+]) = ([\-+. \ de] +)/, // If (type = "string" & (ret = rrelnum.exe C (value) {/** RET [1] Positive and negative; RET [2] relative value * + (Ret [1] + 1) RET [1] is a string, plus 1 to '+ 1' or'-1 ', the plus sign on the frontend side converts a string to a number 1 or-1 * + RET [2] the same plus sign converts RET [2] to a number * plus or minus 1 multiplied by the relative value and then the current value., obtain the value */value = (+ (Ret [1] + 1) * + RET [2]) + P Arsefloat (jquery.css (ELEM, name); // fixes bug #9237 // #9237 :. CSS () does not work on the property with a hyphen. In 1.6.2, modify type = "Number";} // make sure that Nan and null values Aren' t set. see: #7116 // filter Nan null without any processing. If you want to delete an attribute from the inline style, please input an empty string if (value = NULL | type = "Number" & isnan (value) {return ;}// if a number was passed in, add 'px 'to the (sequence T for certain CSS properties) // If a number is uploaded, add the unit px(jquery.css numbe For the semantics defined in r, see the definition of jquery.css number.) If (type = "Number "&&! Jquery.css number [origname]) {value + = "PX";} // The frontend is a foreplay: filter invalid parameters, calculate relative values, append unit suffix // If a hook was provided, use that value, otherwise just set the specified value/** if there is a hook hooks, if the set function exists in hooks, the Hooks is called. set, assign the return value to value * If hooks. if the returned value of set is undefined, no operation is performed. If the returned value is not undefined, set the style value with the new value * Simply put, there is hooks. set is called, replace value with the return value, and set the style. name; otherwise, set style directly. name * the function of the visible hook is to correct the attribute value and does not directly set the value * Equivalent logic: * <PRE> * If (hooks & "Set" in hooks) {* value = hooks. Set (ELEM, value); * If (value! = Undefined) style [name] = value; *} else {* style [name] = value; *} * </PRE> */If (! Hooks |! ("Set" in hooks) | (value = hooks. Set (ELEM, value ))! = Undefined) {// wrapped to prevent ie from throwing errors when 'invalid' values are provided // fixes bug #5509 // use try-Catch Block to prevent IE, when a style value is set with an invalid value, an exception is thrown. Try {style [name] = value;} catch (E) {} // read} else {// If a hook was provided get the non-computed value from there // If hooks exists, Hooks is called. get, the returned value is assigned to retif (hooks & "get" in hooks & (ret = hooks. get (ELEM, false, extra ))! = Undefined) {return ret;} // otherwise just get the value from the style object // otherwise, the attribute value return style [name] is read from the style object;}
Jquery.css (ELEM, name, extra)
Jquery.css ()Reads style values.
This method has roughly done the following::
1. convert to the camper type and correct the attribute name
2. If a hook exists, call the get
3. Otherwise, curcss is called. Different browsers call different methods:
IE: getcomputedstyle, ELEM. ownerdocument. defaultview. getcomputedstyle (ELEM, null). getpropertyvalue (name)
W3C: currentstyle, ELEM. currentstyle [name]
LookSource code comments:
// Read the style value CSS: function (ELEM, name, extra) {var ret, hooks; // make sure that we're working with the right namename = jquery. camelcase (name); // convert to camel hooks = jquery.css hooks [name]; // whether there is a hook name = jquery.css props [name] | Name; // modify the attribute name // cssfloat needs a special treatment // cssfloat requires special processing. (is stylefloat not required ?) If (name = "cssfloat") {name = "float"; // switch it back !} // If a hook was provided get the computed value from there // If the hook hooks exists, the Hooks is called. get calculates the style value, and returns if (hooks & "get" in hooks & (ret = hooks. get (ELEM, true, extra ))! = Undefined) {return ret; // otherwise, if a way to get the computed value exists, use that // otherwise, if curcss exists, call curcss to obtain the calculated style value and return} else if (curcss) {return curcss (ELEM, name );}}
Curcss (ELEM, name)
/*** Standard */If (document. defaultview & document. defaultview. getcomputedstyle) {getcomputedstyle = function (ELEM, name) {var ret, defaultview, computedstyle; // pre-defined variable // converts a camper to a hyphen, for example, margintop> margin-top // rupper =/([A-Z] | ^ MS)/g, name = Name. replace (rupper, "-$1 "). tolowercase ();/** decomposition: * var defaultview = ELEM & ELEM. ownerdocument. defaultview; * var computedstyle = defaultview & defaultvie W. getcomputedstyle (ELEM, null); * var ret = computedstyle & computedstyle. getpropertyvalue (name); * return ret; */If (defaultview = ELEM. ownerdocument. defaultview) & (computedstyle = defaultview. getcomputedstyle (ELEM, null) {ret = computedstyle. getpropertyvalue (name); // do not understand what this line is doing? If (ret = ""&&! Jquery. contains (elem.ownerdocument.doc umentelement, ELEM) {ret = jquery. style (ELEM, name) ;}} return ret ;}}/ *** ie */If (document.doc umentelement. currentstyle) {currentstyle = function (ELEM, name) {var left, rsleft, uncomputed, ret = ELEM. currentstyle & ELEM. currentstyle [name], // you can directly set the value to style = ELEM. style; // avoid setting ret to empty string here // so we don't default to auto/** avoid returning null characters String, do not understand? * If ELEM. currentstyle [name] returns NULL. Use style [name] To try */If (ret = NULL & Style & (uncomputed = style [name]). {ret = uncomputed;} // from the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291// if we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels/** does not process General pixel values, but if the unit is strange, it needs to be corrected to pixel PX * Rnumpx =/^ -? \ D + (?: Px )? $/I, // optional negative signs plus numbers and optional PX, check the value * rnum =/^ -? \ D/, // integer, cannot be written in the format of + 1 (should be supported). ** the number is followed by a non-pixel unit ** and cannot be understood, it should be the unit, auto, fontsize */If (! Rnumpx. test (RET) & rnum. test (RET) {// remember the original values // record original value left = style. left; rsleft = ELEM. runtimestyle & ELEM. runtimestyle. left; // put in the new values to get a computed value outif (rsleft) {ELEM. runtimestyle. left = ELEM. currentstyle. left;} style. left = Name = "fontsize "? "1em": (Ret | 0); ret = style. pixelleft + "PX"; // revert the changed valuesstyle. left = left; If (rsleft) {ELEM. runtimestyle. left = rsleft;} return ret = ""? "Auto": Ret ;};} curcss = getcomputedstyle | currentstyle;
Note: I am proficient in CSS but not proficient in it. I have many questions when I look at the source code. If I don't understand it, I will mark it in the text. If you can answer questions or have good reference materials, I will make a lot of bricks. I, this article, and this series are not authoritative. Please be skeptical.