溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

[置頂]       jQuery亂談(七)

發(fā)布時間:2020-09-15 15:43:38 來源:網(wǎng)絡(luò) 閱讀:300 作者:873582595 欄目:web開發(fā)

今天主要分析jQuery處理元素CSS相關(guān)屬性的內(nèi)部實現(xiàn)。相關(guān)方法:addClass()、hasClass()、removeClass()、toggleClass()、css()、jQuery.cssHooks、height()、width()、innerHeight()、innerWidth()、outerHeight()、outerWidth()、offset()、position()、scrollLeft()、scrollTop()。其中addClass()、hasClass()、removeClass()、toggleClass()在前面的jQuery亂談(五)jQuery亂談(六)已經(jīng)分析過,這里不再嘮叨。

  css():

css: function( name, value ) {         return jQuery.access( this, function( elem, name, value ) {             return value !== undefined ?                 jQuery.style( elem, name, value ) :                 jQuery.css( elem, name );         }, name, value, arguments.length > 1 );     }

  該方法可以接受兩個參數(shù),第二個參數(shù)是可選的。當(dāng)該方法只接收一個參數(shù)時,該參數(shù)有兩個意義,若只是一個css屬性名字符串,方法可以返回匹配元素集合中的第一個元素的參數(shù)樣式屬性值;若該參數(shù)是一個CSS屬性-值對象,則對所有的匹配元素設(shè)置相應(yīng)的CSS屬性。當(dāng)接收兩個參數(shù)時,為匹配的所有元素設(shè)置相應(yīng)的CSS屬性。

.css( propertyName ) 

為匹配的元素集合中獲取第一個元素的樣式屬性值。

  • .css( propertyName )

    propertyName         一個css屬性名

.css( propertyName, value ) 

為匹配的元素設(shè)置一個或多個CSS屬性。

  • .css( propertyName, value )

    propertyName                             一個CSS屬性名

    value                                          一個CSS屬性名的值

  • .css( propertyName, function(index, value) )

    propertyName                            一個CSS屬性名

    function(index, value)                一個返回設(shè)置值的函數(shù)。接收元素的索引位置和元素舊的樣式屬性值作為參數(shù)。

  • .css( map )

    map                                         CSS屬性值( property-value)對象映射.

 

  CSS()方法在內(nèi)部實現(xiàn)上使用了jQuery.access()方法,這個全局內(nèi)部方法主要用于.css()、.attr()、.prop()。你可以把它想象成一個集裝箱,我們只要把參數(shù)交給他就可以了,具體的實現(xiàn)不用我們關(guān)注。這里我們主要關(guān)注:

function( elem, name, value ) {             return value !== undefined ?                 jQuery.style( elem, name, value ) :                 jQuery.css( elem, name );         }

  該參數(shù)會自行判斷.css()方法提供了幾個參數(shù),然后分別執(zhí)行對應(yīng)的方法:jQuery.style()、jQuery.css()。

  jQuery.style()主要負責(zé)在DOM節(jié)點上讀取或設(shè)置樣式屬性,該方法主要作用如下:過濾Text和Comment節(jié)點,過濾掉無style的元素,返回undefined;屬性名轉(zhuǎn)換為駝峰式;設(shè)置或讀取樣式。源碼分析如下:

// 在DOM節(jié)點上讀取或設(shè)置樣式屬性 style: function( elem, name, value, extra ) {     // 過濾Text和Comment,如果沒有style屬性也直接返回     if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.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 ]; // 轉(zhuǎn)換為駝峰格式     // 修正屬性名,是否在不同的瀏覽器中使用不同的屬性名     name = jQuery.cssProps[ origName ] || origName; // CSS鉤子      // Check if we're setting a value     // 設(shè)置     if ( value !== undefined ) {         type = typeof value;          // 計算相對值 rrelNum = /^([\-+])=([\-+.\de]+)/, //         if ( type === "string" && (ret = rrelNum.exec( value )) ) {             /*              * ret[1] 正負;ret[2] 相對值              * +( ret[1] + 1) ret[1]是字符串,加上1變成'+1'或'-1',最前邊的加號將字符串轉(zhuǎn)換為數(shù)字1或-1              * +ret[2] 同樣的加號將ret[2]轉(zhuǎn)換為數(shù)字              * 正負1 乘以 相對值 再加上 當(dāng)前值,得出要設(shè)置的值              */             // #9237:.css()在帶有連字符的屬性上不能工作,在1.6.2中修正             type = "number";         }          // 過濾NaN null,不做任何處理,如果想從內(nèi)聯(lián)樣式中刪除某個屬性,請傳入空字符串         if ( value == null || type === "number" && isNaN( value ) ) {             return;         }          // 如果傳入一個數(shù)字,追加單位px(jQuery.cssNumber中定義的屬性除外,見jQuery.cssNumber的定義)         if ( type === "number" && !jQuery.cssNumber[ origName ] ) {             value += "px";         }          // 前邊的都是前戲:過濾非法參數(shù)、計算相對值、追加單位后綴          /*          * 如果有鉤子hooks,且hooks中存在set函數(shù),則調(diào)用hooks.set,將返回值賦給value          * 如果hooks.set的返回值為undefined,則不執(zhí)行任何操作;返回值不為undefined,則用新value設(shè)置樣式值          * 簡單點說,有hooks.set則調(diào)用,用返回值替換value,最后設(shè)置style.name;否則直接設(shè)置style.name          * 可見鉤子的作用是修正屬性值,并不直接對值進行設(shè)置          * 等價的邏輯:          * <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 ) {              // 用try-catch塊,預(yù)防在IE中,當(dāng)用不合法的值設(shè)置樣式值時,拋出異常             try {                 style[ name ] = value;             } catch(e) {}         }     // 讀取     } else {         // 如果有鉤子hooks,則調(diào)用hooks.get,返回值賦給ret         if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {             return ret;         }          // 否則從style對象中讀取屬性值         return style[ name ];     } }

  讀取和設(shè)置樣式表遇到的難題是瀏覽器兼容性。例如訪問樣式屬性時的方式就不同

// W3C var defaultView = elem && elem.ownerDocument.defaultView; var computedStyle = defaultView && defaultView.getComputedStyle( elem, null ); var ret = computedStyle && computedStyle.getPropertyValue( name ); return ret; // IE var ret = elem.currentStyle && elem.currentStyle[ name ] return ret;

  另一個常見的兼容問題是,某些屬性在不同的瀏覽器中使用不同的屬性名,例如float,在IE的DOM實現(xiàn)中用styleFloat,而在遵守W3C標(biāo)準的瀏覽器中是 cssFloat。另外,多個單詞組成的樣式屬性在CSS和DOM有著不一樣的格式,jquery通過方法jQuery.camelCase()將連詞符格式轉(zhuǎn)為駝峰格式。

  

  接著是jQuery.css() ,該方法負責(zé)讀取樣式值。它主要完成如下任務(wù):屬性名轉(zhuǎn)換為駝峰式;如果有鉤子,則調(diào)用鉤子的get;否則調(diào)用curCSS,不同的瀏覽器調(diào)用不同的方法:

    IE:getComputedStyle,elem.ownerDocument.defaultView.getComputedStyle( elem, null ).getPropertyValue( name )

    W3C:currentStyle,elem.currentStyle[ name ]

  源碼分析如下:

// 讀取樣式值 css: function( elem, name, extra ) {     var ret, hooks;      name = jQuery.camelCase( name ); // 轉(zhuǎn)換為駝峰式     hooks = jQuery.cssHooks[ name ]; // 是否有鉤子     name = jQuery.cssProps[ name ] || name; // 修正屬性名      // cssFloat需要特殊處理,(styleFloat不需要嗎?)     if ( name === "cssFloat" ) {         name = "float"; // 又把它轉(zhuǎn)換回去了!     }      // 如果鉤子hooks存在,則調(diào)用hooks.get計算樣式值,并返回     if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {         return ret;           // 否則,如果curCSS存在,則調(diào)用curCSS獲取計算后的樣式值,并返回     } else if ( curCSS ) {         return curCSS( elem, name );     } }

  里面又涉及到了curCSS( elem, name ),該方法主要將getComputedStyle或currentStyle統(tǒng)一,代碼分析如下:

// W3C
if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, name ) { var ret, defaultView, computedStyle; // 預(yù)定義變量 // 將駝峰式轉(zhuǎn)換為連字符,例如marginTop > margin-top // rupper = /([A-Z]|^ms)/g, name = name.replace( rupper, "-$1" ).toLowerCase(); /* * 分解: * var defaultView = elem && elem.ownerDocument.defaultView; * var computedStyle = defaultView && defaultView.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 ); if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } } return ret; }; }
// IE if ( document.documentElement.currentStyle ) { currentStyle = function( elem, name ) { var left, rsLeft, uncomputed, ret = elem.currentStyle && elem.currentStyle[ name ], // 直接就取值 style = elem.style; /* * 避免返回空字符串 * 如果elem.currentStyle[ name ]返回null,用style[name]試試 */ if ( ret === null && style && (uncomputed = style[ name ]) ) { ret = uncomputed; } /* * 不處理一般的像素值,但是如果單位很奇怪就需要修正為像素px * rnumpx = /^-?\d+(?:px)?$/i, // 可選的負號 加 數(shù)字 加 可選的px,對數(shù)值進行檢查 * rnum = /^-?\d/, // 整數(shù),不支持+1這樣的寫法(應(yīng)該支持) * * 數(shù)字后跟了非像素單位 * * */ if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { // Remember the original values // 記錄原始值 left = style.left; rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ( ret || 0 ); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } curCSS = getComputedStyle || currentStyle;

  jQuery.cssHooks主要用于修正CSS樣式屬性在瀏覽器中的差異。例如:opacity等。代碼很簡單,就不分析了:

cssHooks: {         opacity: {             get: function( elem, computed ) {                 if ( computed ) {                     // We should always get a number back from opacity                     var ret = curCSS( elem, "opacity" );                     return ret === "" ? "1" : ret;                  }             }         }     }

  已經(jīng)寫的夠多了,下一篇再分析height()、width()、innerHeight()、innerWidth()、outerHeight()、outerWidth()、offset()、position()、scrollLeft()、scrollTop()。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI