樣式操作模塊可用于管理DOM元素的樣式、坐標和尺寸,本節講解一下樣式相關,樣式操作通過jQuery實體的css方法來實作,該方法有很多的執行方法,如下:
- css(obj) ;引數1是一個物件時,表示一次性設定多個css樣式
- css(name,func) ;引數2是函式時,設定的是函式回傳值
- css(name,'') ;引數2是空字串時,表示洗掉該樣式(洗掉style屬性上的)
- css(name) ;如果忽略第二個引數,則獲取第一個匹配元素的name樣式
- css(name,value) ;設定每個匹配的元素的name樣式為值value,
writer by:大沙漠 QQ:22969969
舉個栗子:
<!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">設定背景和邊框</button> <button id="b2">移除邊框</button> <button id="b3">獲取寬度</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>
效果如下:

我們設定了三個按鈕,分別通過css方法進行設定、洗掉和獲取樣式,比較好用哈
原始碼分析
jquery實體css方法實作如下:
jQuery.fn.css = function( name, value ) { //獲取匹配元素集合中第一個元素的計算樣式 或者 在每個匹配元素上設定一個或多個行內樣式, // Setting 'undefined' is a no-op if ( arguments.length === 2 && value =https://www.cnblogs.com/greatdesert/p/== undefined ) { return this; } return jQuery.access( this, name, value, true, function( elem, name, value ) { //呼叫jQuery.access()遍歷匹配元素集合,并在每個元素上執行傳入的回呼函式 return value !== undefined ? jQuery.style( elem, name, value ) : //如果傳入了引數則呼叫jQuery.style()設定行內樣式 jQuery.css( elem, name ); //否則呼叫jQuery.css()來讀取計算樣式 }); };
通過access工具函式來實作的,這樣引數就支持多種形式了,access在html篇里講解過了,可以看這個地址:https://www.cnblogs.com/greatdesert/p/11670682.html
可以原始碼看到,jQuery內部對于css的實作是通過靜態的style和css方法來實作的,前者負責設定DOM元素的行內樣式,后者用于讀取elem元素上name的值,style的實作如下:
jQuery.extend({ style: function( elem, name, value, extra ) { //讀取或設定DOM元素的行內樣式,elem:DOM元素、name:待讀取或設定的樣式名、value:待設定的樣式值、extra:用于指示獲取寬度、高度的計算公式字串, // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { //如果是文本節點或注釋節點 或者不是文本、注釋節點但是沒有style屬性 return; //直接回傳,不做處理 } // Make sure that we're working with the right name var ret, type, origName = jQuery.camelCase( name ), style = elem.style, hooks = jQuery.cssHooks[ origName ]; //將style設定為elem.style name = jQuery.cssProps[ origName ] || origName; // Check if we're setting a value if ( value !== undefined ) { //如果傳入了value值,則設定相對值, type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { //如果value是相對值字串,則計算相對值,value格式是+=..或-=...,rrelNum = /^([\-+])=([\-+.\de]+)/, value = https://www.cnblogs.com/greatdesert/p/( +( 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 =https://www.cnblogs.com/greatdesert/p/= null || type === "number" && isNaN( value ) ) { //過濾null、NaN型別,不做任何處理,如果要洗掉某個行內樣式,請傳入空字串 return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { //如果待設定的樣式值是一個數值,且該樣式不在cssNumber中定義的,則自動追加單位px,cssNumber定義在6492行,是一個陣列, value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = https://www.cnblogs.com/greatdesert/p/hooks.set( elem, value )) !== undefined ) { //優先呼叫修正物件愛那個的修正方法set(); // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; //其次設定style[name]屬性, } catch(e) {} } } else { //如果未傳入value引數,則讀取行內樣式, // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { //優先呼叫修正物件的get()修正方法,并回傳, return ret; } // Otherwise just get the value from the style object return style[ name ]; //沒有修正方法則讀取屬性style[name], } }, })
從原始碼里看到我們可以每次遞增一些屬性,例如:$("div").css('width','+=20')這樣去累加寬度的,默認單位為px,
對于css的實作如下:
jQuery.extend({ css: function( elem, name, extra ) { //負責讀取DOM元素的計算樣式,elem:待讀取的DOM元素,name:待設定的樣式名,extra:一個字串,用于指示獲取高度、寬度的計算公式, var ret, hooks; // Make sure that we're working with the right name name = jQuery.camelCase( name ); //將樣式名轉換為駝峰式 hooks = jQuery.cssHooks[ name ]; //hooks指向駝峰式樣式名對應的修正物件, name = jQuery.cssProps[ name ] || name; //修正駝峰式樣式名,如果origName是float則把name修正為cssFloat或styleFloat // cssFloat needs a special treatment if ( name === "cssFloat" ) { //如果樣式名為cssFloat name = "float"; //則修正為float } // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { //優先呼叫修正物件的get()修正方法, return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name ); //其他呼叫curCSS(elem,name)讀取計算樣式,定義在6765行 } }, })
curCSS是jQuery內部定義的一個工具函式,用于獲取某個樣式,實作如下:
curCSS = getComputedStyle || currentStyle;
默認等于getComputedStyle(window.getComputedStyle存在的情況下,IE及其它瀏覽器),currentStyle是jQuery內部實作的一個另一個兼容方案,就不討論了,getComputedStyle實作如下:
if ( document.defaultView && document.defaultView.getComputedStyle ) { //在IE9+和其他瀏覽器中,如果window.getComputedStyle屬性存在,document.defaultView即window物件, getComputedStyle = function( elem, name ) { ////定義getComputedStyle()函式 var ret, defaultView, computedStyle; name = name.replace( rupper, "-$1" ).toLowerCase(); //將可能的駝峰式央視名轉換為連字符式,rupper = /([A-Z]|^ms)/g, if ( (defaultView = elem.ownerDocument.defaultView) && (computedStyle = defaultView.getComputedStyle( elem, null )) ) { //defaultView即window物件 呼叫window.getComputedStyle()方法獲取該節點的樣式集合 ret = computedStyle.getPropertyValue( name ); //呼叫getPropertyValue()方法獲取name樣式的值, if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { //如果沒取到計算樣式,并且當前元素不再檔案中 ret = jQuery.style( elem, name ); //呼叫jQuery.style()讀取行內樣式, } } return ret; }; }
通過代碼可以看到jQuery優先呼叫window.getComputedStyle()屬性獲取樣式的,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/28073.html
標籤:jQuery
上一篇:前端之jQuery
下一篇:jquery 屬性名修改
