jQuery height() innerHeight() outerHight() width() innerWidth() outerWidth()源码解读


在第二层each,传入的对象以height举例是这样的,

{padding:innerHeight,content:height,"":outerHeight}
对它遍历调用function(defaultExtra,funcName),也就是说传入的defaultExtra是键 padding/content/"",而funcName是对应的innerHeight,height,outerHeight。

jQuery.fn[funcName]内部有四个分支:
1、$(window).height()
这时直接返回window.document.documentElement.clientHeight

2、$(document).height()
                    return Math.max(
                        elem.body[ "scroll" + name ], doc[ "scroll" + name ],
                        elem.body[ "offset" + name ], doc[ "offset" + name ],
                        doc[ "client" + name ]
                    );

显而易见,它返回的是这5个值中的最大值。

 

3、如果取值,调用jQuery.css()

4、如果是赋值,调用jQuery.style()

 

最后这两个分支内部比较复杂,jQuery.css,cssHooks,cssProps是重点= =,等以后详细看的时候再写吧。

jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
    jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
        // Margin is only for outerHeight, outerWidth
        jQuery.fn[ funcName ] = function( margin, value ) {
            var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
                extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
            return access( this, function( elem, type, value ) {
                var doc;

                if ( jQuery.isWindow( elem ) ) {
                    // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
                    // isn't a whole lot we can do. See pull request at this URL for discussion:
                    // https://github.com/jquery/jquery/pull/764
                    return elem.document.documentElement[ "client" + name ];
                }

                // Get document width or height
                if ( elem.nodeType === 9 ) {
                    doc = elem.documentElement;

                    // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
                    // whichever is greatest
                    return Math.max(
                        elem.body[ "scroll" + name ], doc[ "scroll" + name ],
                        elem.body[ "offset" + name ], doc[ "offset" + name ],
                        doc[ "client" + name ]
                    );
                }
                return value === undefined ?
                    // Get width or height on the element, requesting but not forcing parseFloat
                    jQuery.css( elem, type, extra ) :

                    // Set width or height on the element
                    jQuery.style( elem, type, value, extra );
            }, type, chainable ? margin : undefined, chainable, null );
        };
    });
});

 

posted on 2015-03-03 16:46  叫我钱了个浅  阅读(632)  评论(0编辑  收藏  举报

导航