学习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

转载于:https://www.cnblogs.com/littledu/articles/2817119.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值