Style manipulation module can be used to manage the style, coordinates and dimensions of DOM elements. This section explains style dependency. Style manipulation is implemented through the css method of the jQuery instance, which has many execution methods, as follows:
- css(obj); when parameter 1 is an object, it means that multiple css styles are set at once
- css(name,func); when parameter 2 is a function, the return value of the function is set.
- css(name,''); when parameter 2 is an empty string, it means deleting the style (on the style property)
- css(name); if the second parameter is ignored, the name style of the first matching element is obtained
- css(name,value); set the name style of each matching element to value.
writer by:Desert QQ:22969969
Lift a chestnut:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="http://libs.baidu.com/jquery/1.7.1/jquery.min.js"></script> <style> div{width: 200px;height: 200px;background: #0ff;} </style> </head> <body> <div> </div> <button id="b1">Set Background and Border</button> <button id="b2">Remove Border</button> <button id="b3">Get Width</button> <script> $('#b1').click(()=>{ $('div').css({background:'#ff0',border:'1px solid #f00'}) }) $('#b2').click(()=>{ $('div').css('border','') }) $('#b3').click(()=>{ $('div').text($('div').css('height') ) }) </script> </body> </html>
The results are as follows:
We set three buttons to set, delete and get styles by css method, which is better for us to use
Source Code Analysis
The jquery instance css method is implemented as follows:
jQuery.fn.css = function( name, value ) { //Gets the calculation style of the first element in the set of matching elements or sets one or more inline styles on each matching element. // Setting 'undefined' is a no-op if ( arguments.length === 2 && value === undefined ) { return this; } return jQuery.access( this, name, value, true, function( elem, name, value ) { //call jQuery.access()Traverse through the set of matching elements and execute the incoming callback function on each element return value !== undefined ? jQuery.style( elem, name, value ) : //Called if a parameter is passed in jQuery.style()Set Inline Style jQuery.css( elem, name ); //Otherwise call jQuery.css()To read the calculation style }); };
Implemented through the access tool function, so that the parameters support a variety of forms, access explained in the html article, you can see this address: https://www.cnblogs.com/greatdesert/p/11670682.html
As you can see from the source code, the internal implementation of css in jQuery is achieved by static style and css methods, which are responsible for setting the inline style of DOM elements, and the latter for reading the value of name on elem elements. The implementation of style is as follows:
jQuery.extend({ style: function( elem, name, value, extra ) { //Read or Set DOM Inline style of the element. elem:DOM Elements, name:The style name to read or set, value:The style values to be set, extra:A string of calculation formulas indicating the width and height to be obtained. // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { //If it is a text or comment node or not a text or comment node but it does not style attribute return; //Return directly without processing } // Make sure that we're working with the right name var ret, type, origName = jQuery.camelCase( name ), style = elem.style, hooks = jQuery.cssHooks[ origName ]; //take style Set to elem.style name = jQuery.cssProps[ origName ] || origName; // Check if we're setting a value if ( value !== undefined ) { //If passed in value Value, then set the relative value. type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { //If value Is the relative value string, then the relative value is calculated. value The format is+=..or-=.... rrelNum = /^([\-+])=([\-+.\de]+)/, value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { //filter null,NaN Type, do nothing, if you want to delete an inline style, pass in an empty string return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { //If the style value to be set is a numeric value and the style is not cssNumber If defined in the px. cssNumber Defined in line 6492, is an array. value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) { //Priority call fix method that fix object loves set(); // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; //SecondlySet up style[name]Properties. } catch(e) {} } } else { //If not passed in value Parameter reads the inline style. // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { //Priority call to fix object's get()Correct the method and return. return ret; } // Otherwise just get the value from the style object return style[ name ]; //Read property without fix style[name]. } }, })
From the source code, we can see that we can increment some attributes each time, for example: $("div").css('width','+=20') so that we can add up the width, the default unit is px.
The implementation for css is as follows:
jQuery.extend({ css: function( elem, name, extra ) { //Responsible for reading DOM The calculation style of the element. elem:Readable DOM element,name:The style name to be set, extra:A string that indicates the calculation formula for obtaining height and width. var ret, hooks; // Make sure that we're working with the right name name = jQuery.camelCase( name ); //Convert Style Name to Hump hooks = jQuery.cssHooks[ name ]; //hooks Point to the correct object for the hump style name. name = jQuery.cssProps[ name ] || name; //Modify Hump Style Name,If origName yes float Then put name Amend to cssFloat or styleFloat // cssFloat needs a special treatment if ( name === "cssFloat" ) { //If the style name is cssFloat name = "float"; //Then amend to float } // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { //Priority call to fix object's get()Correction method. return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name ); //Other Calls curCSS(elem,name)Read the calculation style.Defined on line 6765 } }, })
curCSS is a tool function defined internally by jQuery to get a style as follows:
curCSS = getComputedStyle || currentStyle;
By default, it is equal to getComputedStyle (IE and other browsers in the case of window.getComputedStyle), which is another compatible scheme implemented internally by jQuery and is not discussed. getComputedStyle implements the following:
if ( document.defaultView && document.defaultView.getComputedStyle ) { //stay IE9+And other browsers.If window.getComputedStyle Property exists. document.defaultView That is window Object. getComputedStyle = function( elem, name ) { ////Define getComputedStyle() function var ret, defaultView, computedStyle; name = name.replace( rupper, "-$1" ).toLowerCase(); //Convert possible hump CCTV names to hyphens. rupper = /([A-Z]|^ms)/g, if ( (defaultView = elem.ownerDocument.defaultView) && (computedStyle = defaultView.getComputedStyle( elem, null )) ) { //defaultView That is window object call window.getComputedStyle()Method to get the style collection for this node ret = computedStyle.getPropertyValue( name ); //call getPropertyValue()Method acquisition name The value of the style. if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { //If the calculation style is not fetched and the current element is no longer in the document ret = jQuery.style( elem, name ); //call jQuery.style()Read inline styles. } } return ret; }; }
You can see from the code that jQuery calls the window.getComputedStyle() property first to get the style.