jQuery 源码解析(二十九) 样式操作模块 尺寸详解

时间:2023-03-08 19:59:38
jQuery 源码解析(二十九) 样式操作模块 尺寸详解

样式操作模块可用于管理DOM元素的样式、坐标和尺寸,本节讲解一下尺寸这一块

jQuery通过样式操作模块里的尺寸相关的API可以很方便的获取一个元素的宽度、高度,而且可以很方便的区分padding、border、 margin等,主要有六个API,如下:

  • heihgt(size)、width(size)       ;获取第一个匹配元素的高度、宽度,或者通过调用.css(name,value)方法来设置高度、宽度。 size可以是字符串或者数值
  • innerHeight()、innerWidth()    ;获取匹配元素集合中第一个元素的高度、宽度,包括内容content、内边距padding。
  • outerHeight(m)、outerWidth(m)      ;获取匹配元素集合中第一个元素的高度、宽度,包括内容content、内边距padding,边框border

举个栗子:

writer by:大沙漠 QQ:22969969

<!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输出结果,控制台输出如下:

jQuery 源码解析(二十九) 样式操作模块 尺寸详解

渲染如下:

jQuery 源码解析(二十九) 样式操作模块 尺寸详解

另外我们在按钮上绑定了事件,点击可以设置div的尺寸,点击效果如下:

jQuery 源码解析(二十九) 样式操作模块 尺寸详解

可以看到,点击按钮后div就变大了,这是因为我们通过width、height设置了参数,修改了它的样式。

源码分析


jQuery对heihgt、width、innerHeight、innerWidth、outerHeight、outerWidth这六个API的实现是通过一个getWH()的工具函数实现的,该函数的定义:getWH(elem,name,extra),参数如下:

  • elem  ;要获取高度、宽度的DOM元素
  • name  ;可选字符串,可以是height、width
  • extra  ;指示了计算宽度和高度的公式字符串,可选,可以设置为padding、border和margin。

函数源码如下:

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,也就是上面所说的工具函数。