样式操做模块可用于管理DOM元素的样式、坐标和尺寸,本节讲解一下尺寸这一块css
jQuery经过样式操做模块里的尺寸相关的API能够很方便的获取一个元素的宽度、高度,并且能够很方便的区分padding、border、 margin等,主要有六个API,以下:html
举个栗子:node
writer by:大沙漠 QQ:22969969jquery
<!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> </head> <body> <style>div {width:80px;height:80px;border:10px solid #cf0;background:#333;margin:20px;padding:5px;color:#fff;}</style> <div>你好</div> <button>测试按钮</button> <script> console.log('width:',$('div').width()); //输出:80 console.log('innerWidth:',$('div').innerWidth()); //输出:90 console.log('outerWidth:',$('div').outerWidth()); //输出:110 $('button').click(function(){ $('div').height(100) $('div').width(100) }) </script> </body> </html>
咱们定义了一个 div和一个按钮,初始化时分别打印包含div的jquery对象的Width、innerWidth和outerWidth输出结果,控制台输出以下:数组
渲染以下:less
另外咱们在按钮上绑定了事件,点击能够设置div的尺寸,点击效果以下:ssh
能够看到,点击按钮后div就变大了,这是由于咱们经过width、height设置了参数,修改了它的样式。ide
源码分析函数
jQuery对heihgt、width、innerHeight、innerWidth、outerHeight、outerWidth这六个API的实现是经过一个getWH()的工具函数实现的,该函数的定义:getWH(elem,name,extra),参数以下:工具
函数源码以下:
var cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ]; function getWH( elem, name, extra ) { //一个工具函数,用于获取元素的高度、宽度,为尺寸方法.width()、.height()、.innerWidth()、innerHeight()等提供了基础功能 // Start with offset property var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, //若是参数name是width则val是elem元素的宽度,不然val是elem元素的高度 其中包含了内容content、内边距padding、边框border,不包含外边距margin。 which = name === "width" ? cssWidth : cssHeight, //若是参数name是width则which等于[ "Left", "Right" ],不然等于[ "Top", "Bottom" ] i = 0, len = which.length; if ( val > 0 ) { //若是元素可见 if ( extra !== "border" ) { //参数不是border的状况下,则根据extra值的不一样 选择性的加减边框border、内边距padding、外边距margin。 for ( ; i < len; i++ ) { //遍历width数组,分别加减Leftpadding、Rightpadding等信息 if ( !extra ) { //若是没有传入extra参数,则减去内边距padding。 val -= parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0; } if ( extra === "margin" ) { //若是参数extra是margin,则加上外边距margin val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0; } else { //执行到这里则表示extra等于padding val -= parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0; } } } return val + "px"; //最后返回val 若是参数是border则返回包含了内容content、内边距padding、边框border的高度,宽度。 } //下面是元素不可见的状况,它会在计算样式或内链样式的基础上,根据参数extra,选择性的加上内边距padding、边框border、外边框margin。有兴趣能够看看 // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, name ); if ( val < 0 || val == null ) { val = elem.style[ name ] || 0; } // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; // Add padding, border, margin if ( extra ) { for ( ; i < len; i++ ) { val += parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0; if ( extra !== "padding" ) { val += parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0; } } } return val + "px"; }
咱们调用width等jquery实例函数时并非直接调用这个getWH()工具函数的,该函数函数是挂载到jQuery.cssHooks上的,以下:
jQuery.each(["height", "width"], function( i, name ) { jQuery.cssHooks[ name ] = { //挂载到jQuery.cssHooks上的 get: function( elem, computed, extra ) { var val; if ( computed ) { if ( elem.offsetWidth !== 0 ) { //若是元素可见 return getWH( elem, name, extra ); //则调用函数getWH(elem,name,extra获取高度、宽度) } else { jQuery.swap( elem, cssShow, function() { val = getWH( elem, name, extra ); }); } return val; } }, set: function( elem, value ) { if ( rnumpx.test( value ) ) { // ignore negative width and height values #1599 value = parseFloat( value ); if ( value >= 0 ) { return value + "px"; } } else { return value; } } }; });
当咱们调用jQuery.css获取一个元素的宽度或高度时(例如调用$.css(div,'width')时,)就会有限调用这个jqueyr.cssHooks里的信息,jquery.css里对于csshooks的实现以下:
jQuery.extend({ css: function( elem, 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; // cssFloat needs a special treatment if ( name === "cssFloat" ) { name = "float"; } // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { //优先调用hooks对象的里的get()修正方法,这里就是上面定义的对于width、height属性的get方法了 return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name ); } }, //... })
了解了getWH()工具函数和经过jQuery.css()会执行getWH函数后,再来看下heihgt、width、innerHeight、innerWidth、outerHeight、outerWidth这六个API的实现,源码以下:
jQuery.each([ "Height", "Width" ], function( i, name ) { //遍历[ "Height", "Width" ] var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn[ "inner" + name ] = function() { //在jQuery实例上添加innerHeight()、innerWidth方法 var elem = this[0]; //获取第一个匹配元素 return elem ? elem.style ? parseFloat( jQuery.css( elem, type, "padding" ) ) : //若是匹配元素有style属性,则调用方法jQuery.css()获取高度、宽度。第三个参数为padding。 this[ type ]() : null; }; // outerHeight and outerWidth jQuery.fn[ "outer" + name ] = function( margin ) { //在jQuery实例上添加定义outerHeight()、outerWidth()方法。 var elem = this[0]; //获取第一个匹配元素 return elem ? elem.style ? parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) : //若是匹配元素有style属性,则调用方法jQuery.css()方法,若是传入了margin,则把margin也算进去 this[ type ]() : null; }; jQuery.fn[ type ] = function( size ) { //在jQuery实例上添加height(size)、width(size)方法 // Get window width or height var elem = this[0]; //获取第一个匹配元素 if ( !elem ) { return size == null ? null : this; } if ( jQuery.isFunction( size ) ) { //若是size参数是函数,则遍历匹配元素集合,在每一个集合上执行该函数,并取其返回值迭代调用方法.height(size)、.width(size)。 return this.each(function( i ) { var self = jQuery( this ); self[ type ]( size.call( this, i, self[ type ]() ) ); }); } if ( jQuery.isWindow( elem ) ) { //若是elem是window对象,则分拿回html或body元素的可见高度clientHeight、可见宽度clientWidth。 // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat var docElemProp = elem.document.documentElement[ "client" + name ], body = elem.document.body; return elem.document.compatMode === "CSS1Compat" && docElemProp || body && body[ "client" + name ] || docElemProp; // Get document width or height } else if ( elem.nodeType === 9 ) { //若是匹配的是documet对象,则读取html元素的clientHeight/Width // Either scroll[Width/Height] or offset[Width/Height], whichever is greater return Math.max( elem.documentElement["client" + name], elem.body["scroll" + name], elem.documentElement["scroll" + name], elem.body["offset" + name], elem.documentElement["offset" + name] ); // Get or set width or height on the element } else if ( size === undefined ) { //若是未传入size参数 var orig = jQuery.css( elem, type ), //调用jQuery.css()读取第一个匹配元素计算后的高度、宽度。 ret = parseFloat( orig ); return jQuery.isNumeric( ret ) ? ret : orig; //返回结果 // Set the width or height on the element (default to pixels if value is unitless) } else { return this.css( type, typeof size === "string" ? size : size + "px" ); //不然调用this.css()设置样式 } }; });
遍历[ "Height", "Width" ]数组,依次在jQuery.fn上挂载属性,内部是经过jQuery.css()获取width或height,也就是上面所说的工具函数。