學習jQuery.support


做前端最痛苦的莫過於兼容問題了,同一樣東西,不同瀏覽器有不同的實現,同一個瀏覽器不同的版本也有不同的處理。直叫人抓狂。但既然做了前端,就不得不提起耐心,面對這些萬惡的兼容。

jQuery作為一個目前來講最流行的JS庫,它同樣提供了檢測各種各樣特性的功能,告訴你某個功能該瀏覽器是否支持,好讓你做出進一步的處理。下面,先羅列一下一些問題吧。

測試瀏覽器:IE6,IE7,IE8,IE9,chrome 23.0.1271.95,firefox 17.0.1,其中IE78是在IE9的文檔模式下,不包准確,但jQuery和網上搜到的結果應該可以相信前人的測試是准確的。另,在chrome23這本版本已修復的bug也不列入。

1. IE678的childNodes不包含空白文本節點,firstChild同理

2. 空table,IE會自動生成tbody,而標准瀏覽器不會(標准瀏覽器如果有tr存在,也會自動生成tbody)

3. IE678無法通過div.innerHTML = '<link />';來插入link,同樣的還有style,script節點

4. IE67無法用getAttribute獲取style,返回object,同理也無法用setAttribute設置style

5. IE67,無法通過getAttribute獲取用戶設定的原始href值

6. IE678是通過filter濾鏡來支持透明度

7. IE678通過styleFloat來獲取float,而標准瀏覽器用cssFloat

8. IE中,第一個option不被默認選中,包括IE9依然如此,其他則選中

9. IE67, 某些特殊屬性的獲取也比較特殊,如class, for, char,不能直接使用getAttribute獲取

10. IE6在克隆HTML5的新標簽元素時outerHTML有":"

11. IE6789,input元素的checked屬性不能被拷貝

12. IE678不能delete節點上的屬性

13. IE會拷貝事件

14. IE下,input被更換類型后,無法保持前一個類型所設的值,蛋疼才會這樣做

越看越覺得悲催,不列了。直接看jQuery的源碼解釋吧。

 

jQuery.support = (function() {
    
    var support,
        all,
        a,
        select,
        opt,
        input,
        fragment,
        eventName,
        i,
        isSupported,
        clickFn,
        div = document.createElement("div");
    
    // Setup
    div.setAttribute( "className", "t" );
    div.innerHTML = "  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
    
    // Support tests won't run in some limited or non-browser environments
    all = div.getElementsByTagName("*");
    a = div.getElementsByTagName("a")[ 0 ];
    if ( !all || !a || !all.length ) {
        return {};
    }
    
    // First batch of tests
    select = document.createElement("select");
    opt = select.appendChild( document.createElement("option") );
    input = div.getElementsByTagName("input")[ 0 ];
    
    a.style.cssText = "top:1px;float:left;opacity:.5";
    support = {
        // IE strips leading whitespace when .innerHTML is used
        // IE678的childNodes不包含空白文本節點,firstChild同理
        leadingWhitespace: ( div.firstChild.nodeType === 3 ),
    
        // Make sure that tbody elements aren't automatically inserted
        // IE will insert them into empty tables
        // 空table,IE會自動生成tbody,而標准瀏覽器不會(標准瀏覽器如果有tr存在,也會自動生成tbody)
        tbody: !div.getElementsByTagName("tbody").length,
    
        // Make sure that link elements get serialized correctly by innerHTML
        // This requires a wrapper element in IE
        // IE678無法通過div.innerHTML = '<link />';來插入link
        htmlSerialize: !!div.getElementsByTagName("link").length,
    
        // Get the style information from getAttribute
        // (IE uses .cssText instead)
        // IE67無法用getAttribute獲取style,返回object,同理也無法用setAttribute設置style
        style: /top/.test( a.getAttribute("style") ),
    
        // Make sure that URLs aren't manipulated
        // (IE normalizes it by default)
        // getAttribute獲取href的問題,詳見http://www.cnblogs.com/littledu/articles/2710234.html
        hrefNormalized: ( a.getAttribute("href") === "/a" ),
    
        // Make sure that element opacity exists
        // (IE uses filter instead)
        // Use a regex to work around a WebKit issue. See #5145
        // IE678是通過filter濾鏡來支持透明度
        opacity: /^0.5/.test( a.style.opacity ),
    
        // Verify style float existence
        // (IE uses styleFloat instead of cssFloat)
        // IE678通過styleFloat來獲取float,而標准瀏覽器用cssFloat
        cssFloat: !!a.style.cssFloat,
    
        // Make sure that if no value is specified for a checkbox
        // that it defaults to "on".
        // (WebKit defaults to "" instead)
        // checkbox的默認值為'on',chrome  23.0.1271.95 m測試
        checkOn: ( input.value === "on" ),
    
        // Make sure that a selected-by-default option has a working selected property.
        // (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
        // IE中,第一個option不被默認選中,包括IE9依然如此,其他則選中
        optSelected: opt.selected,
    
        // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
        // IE67無法通過setAttribute('class','ooxx')來設置className(IE67支持setAttribute('className','ooxx')),其他瀏覽器則可以,反之getAttribute同理
        getSetAttribute: div.className !== "t",
    
        // Tests for enctype support on a form (#6743)
        // 本機所有瀏覽器支持一樣ie6789,chrome,ff
        enctype: !!document.createElement("form").enctype,
    
        // Makes sure cloning an html5 element does not cause problems
        // Where outerHTML is undefined, this still works
        // IE6在克隆HTML5的新標簽元素時outerHTML有":"
        html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
    
        // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
        // 檢測詭異模式,也就是IE6沒有doctype時的模式
        boxModel: ( document.compatMode === "CSS1Compat" ),
    
        // Will be defined later
        submitBubbles: true,
        changeBubbles: true,
        focusinBubbles: false,
        deleteExpando: true,
        noCloneEvent: true,
        inlineBlockNeedsLayout: false,
        shrinkWrapBlocks: false,
        reliableMarginRight: true,
        boxSizingReliable: true,
        pixelPosition: false
    };
    
    // Make sure checked status is properly cloned
    // IE6789,checked不能被拷貝
    input.checked = true;
    support.noCloneChecked = input.cloneNode( true ).checked;
    
    // Make sure that the options inside disabled selects aren't marked as disabled
    // (WebKit marks them as disabled)
    // chrome23已修復
    select.disabled = true;
    support.optDisabled = !opt.disabled;
    
    // Test to see if it's possible to delete an expando from an element
    // Fails in Internet Explorer
    // IE678不能delete節點上的屬性
    try {
        delete div.test;
    } catch( e ) {
        support.deleteExpando = false;
    }
    
    //IE會拷貝事件
    if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
        div.attachEvent( "onclick", clickFn = function() {
            // Cloning a node shouldn't copy over any
            // bound event handlers (IE does this)
            support.noCloneEvent = false;
        });
        div.cloneNode( true ).fireEvent("onclick");
        div.detachEvent( "onclick", clickFn );
    }
    
    // Check if a radio maintains its value
    // after being appended to the DOM
    // IE下,input被更換類型后,無法保持前一個類型所設的值,蛋疼
    input = document.createElement("input");
    input.value = "t";
    input.setAttribute( "type", "radio" );
    support.radioValue = input.value === "t";
    
    input.setAttribute( "checked", "checked" );
    
    // #11217 - WebKit loses check when the name is after the checked attribute
    // chrome23已修復
    input.setAttribute( "name", "t" );
    
    div.appendChild( input );
    fragment = document.createDocumentFragment();
    fragment.appendChild( div.lastChild );
    
    // WebKit doesn't clone checked state correctly in fragments
    // chrome23已修復 
    support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
    
    // Check if a disconnected checkbox will retain its checked
    // value of true after appended to the DOM (IE6/7)
    support.appendChecked = input.checked;
    
    fragment.removeChild( input );
    fragment.appendChild( div );
    
    // Technique from Juriy Zaytsev
    // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
    // We only care about the case where non-standard event systems
    // are used, namely in IE. Short-circuiting here helps us to
    // avoid an eval call (in setAttribute) which can cause CSP
    // to go haywire. See: https://developer.mozilla.org/en/Security/CSP
    // 檢測事件類型,如果上面的英文文章看不懂,推薦看這篇:http://www.cnblogs.com/GrayZhang/archive/2010/10/29/feature-detection-event.html
    if ( div.attachEvent ) {
        for ( i in {
            submit: true,
            change: true,
            focusin: true
        }) {
            eventName = "on" + i;
            isSupported = ( eventName in div );
            if ( !isSupported ) {
                div.setAttribute( eventName, "return;" );
                isSupported = ( typeof div[ eventName ] === "function" );
            }
            support[ i + "Bubbles" ] = isSupported;
        }
    }
    
    // Run tests that need a body at doc ready
    jQuery(function() {
        var container, div, tds, marginDiv,
            divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
            body = document.getElementsByTagName("body")[0];
    
        if ( !body ) {
            // Return for frameset docs that don't have a body
            return;
        }
    
        container = document.createElement("div");
        container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";
        body.insertBefore( container, body.firstChild );
    
        // Construct the test element
        div = document.createElement("div");
        container.appendChild( div );
    
        // Check if table cells still have offsetWidth/Height when they are set
        // to display:none and there are still other visible table cells in a
        // table row; if so, offsetWidth/Height are not reliable for use when
        // determining if an element has been hidden directly using
        // display:none (it is still safe to use offsets if a parent element is
        // hidden; don safety goggles and see bug #4512 for more information).
        // (only IE 8 fails this test)
        // 把上面英文翻譯了就知道是什么意思了
        div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
        tds = div.getElementsByTagName("td");
        tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
        isSupported = ( tds[ 0 ].offsetHeight === 0 );
    
        tds[ 0 ].style.display = "";
        tds[ 1 ].style.display = "none";
    
        // Check if empty table cells still have offsetWidth/Height
        // (IE <= 8 fail this test)
        support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
    
        // Check box-sizing and margin behavior
        div.innerHTML = "";
        div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
        //檢測是否支持box-sizing
        support.boxSizing = ( div.offsetWidth === 4 );
        support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
    
        // NOTE: To any future maintainer, we've window.getComputedStyle
        // because jsdom on node.js will break without it.
        if ( window.getComputedStyle ) {
            support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
            support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
    
            // Check if div with explicit width and no margin-right incorrectly
            // gets computed margin-right based on width of container. For more
            // info see bug #3333
            // Fails in WebKit before Feb 2011 nightlies
            // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
            marginDiv = document.createElement("div");
            marginDiv.style.cssText = div.style.cssText = divReset;
            marginDiv.style.marginRight = marginDiv.style.width = "0";
            div.style.width = "1px";
            div.appendChild( marginDiv );
            support.reliableMarginRight =
                !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
        }
    
        if ( typeof div.style.zoom !== "undefined" ) {
            // Check if natively block-level elements act like inline-block
            // elements when setting their display to 'inline' and giving
            // them layout
            // (IE < 8 does this)
            // IE67,block的元素設置了inline+zoom后,特性會表現的跟inline-block一樣,這里是通過offsetWidth來計算
            // inline元素是不算width的,所以輸出offsetWidth會是2(因為padding:1px),而IE67下表現為inline-block,所以輸出為3
            div.innerHTML = "";
            div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
            support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
    
            // Check if elements with layout shrink-wrap their children
            // (IE 6 does this)
            div.style.display = "block";
            div.style.overflow = "visible";
            div.innerHTML = "<div></div>";
            div.firstChild.style.width = "5px";
            support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
    
            container.style.zoom = 1;
        }
    
        // Null elements to avoid leaks in IE
        body.removeChild( container );
        container = div = tds = marginDiv = null;
    });
    
    // Null elements to avoid leaks in IE
    fragment.removeChild( div );
    all = a = select = opt = input = fragment = div = null;
    
    return support;
})();

jQuery版本 1.8.3


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM