dojo/dom-geometry元素大小

时间:2023-03-09 01:45:36
dojo/dom-geometry元素大小

  在进入源码分析前,我们先来点基础知识。下面这张图画的是元素的盒式模型,这个没有兼容性问题,有问题的是元素的宽高怎么算。以宽度为例,ff中 元素宽度=content宽度,而在ie中 元素宽度=content宽度+border宽度+padding宽度。IE8中加入了box-sizzing,该css属性有两个值:border-box、content-box分别对应ie和ff中元素宽度的工作方式。

dojo/dom-geometry元素大小

  偏移量:offsetLeft、offsetTop、offsetWidth、offsetHeight

  offsetLeft:包含元素的左内边框到元素的左外边框之间的像素距离。

  offsetTop:包含元素的上内边框到元素的上外边框之间的相续距离。

  offsetWidth:包括元素的内容区宽度、左右内边距宽度、左右边框宽度、垂直方向滚动条的宽度之和。

  offsetHeight:包括元素内容区高度、左右内边距高度、左右边框高度、水平方向滚动条的高度之和。

  包含元素的引用在offsetParent属性中,offsetParent属性不一定与parentNode属性相同,比如<td>的offsetParent是<table>而不是<tr>.

dojo/dom-geometry元素大小

  客户区大小:clientWidth、clientHeight

  clientWidth:元素的内容区宽度+内边距宽度

  clientHeight:元素的内容区高度+内边距高度

dojo/dom-geometry元素大小

  滚动大小:scrollTop、scrollLeft、scrollWidth、scrollHeight。滚动大小指的是包含滚动内容的元素大小。

  scrollTop:被隐藏在内容区域上方的像素数。

  scrollLeft:被隐藏在内容区域左侧的像素数。

  通过设置以上两个属性可以改变元素的滚动位置。

  scrollWidth:在没有滚动条情况下,元素的内容的宽度。

  scrollHeight:在没有滚动条情况下,元素内容的高度。

dojo/dom-geometry元素大小

  以上基础知识,对我们分析dom-geometry模块的代码会有不少帮助。下面我们进入源码学习阶段。

  dom-geometry模块封装了许多跟盒式模型相关的函数,主要涉及:content、padding、border、margin四方面。在前面的几篇文章中我们多次提到,前端js库中对dom操作的封装最终都是要用到DOM原生的API。在此模块中,最常用的原生方法就是elemet.ownerDocument.defaultView.getComputedStyle和element.getBoundingClientRect。尽管这两个方法都存在着兼容性问题,但我们都有适当的方法来解决。

  getComputedStyle方法已经在dom-style模块中介绍过(ie中使用element.currentStyle其他浏览器利用原生的getComputedStyle,在webkit中对于不在正常文档流中的元素先改变display),这里简单看一下:

 if(has("webkit")){
getComputedStyle = function(/*DomNode*/ node){
var s;
if(node.nodeType == 1){
var dv = node.ownerDocument.defaultView;
s = dv.getComputedStyle(node, null);
if(!s && node.style){
node.style.display = "";
s = dv.getComputedStyle(node, null);
}
}
return s || {};
};
}else if(has("ie") && (has("ie") < 9 || has("quirks"))){
getComputedStyle = function(node){
// IE (as of 7) doesn't expose Element like sane browsers
// currentStyle can be null on IE8!
return node.nodeType == 1 /* ELEMENT_NODE*/ && node.currentStyle ? node.currentStyle : {};
};
}else{
getComputedStyle = function(node){
return node.nodeType == 1 /* ELEMENT_NODE*/ ?
node.ownerDocument.defaultView.getComputedStyle(node, null) : {};
};
}
style.getComputedStyle = getComputedStyle;

  getComputedStyle得到的某些计算后样式是带有单位的,我们要把单位去掉。这里依赖dom-style中的toPixelValue方法:

 var toPixel;
if(!has("ie")){
toPixel = function(element, value){
// style values can be floats, client code may want
// to round for integer pixels.
return parseFloat(value) || 0;
};
}else{
toPixel = function(element, avalue){
if(!avalue){ return 0; }
// on IE7, medium is usually 4 pixels
if(avalue == "medium"){ return 4; }
// style values can be floats, client code may
// want to round this value for integer pixels.
if(avalue.slice && avalue.slice(-2) == 'px'){ return parseFloat(avalue); }
var s = element.style, rs = element.runtimeStyle, cs = element.currentStyle,
sLeft = s.left, rsLeft = rs.left;
rs.left = cs.left;
try{
// 'avalue' may be incompatible with style.left, which can cause IE to throw
// this has been observed for border widths using "thin", "medium", "thick" constants
// those particular constants could be trapped by a lookup
// but perhaps there are more
s.left = avalue;
avalue = s.pixelLeft;
}catch(e){
avalue = 0;
}
s.left = sLeft;
rs.left = rsLeft;
return avalue;
};
}
style.toPixelValue = toPixel;

  函数有点复杂,对于ie浏览器只要看懂这句就行:if(avalue.slice && avalue.slice(-2) == 'px'){ return parseFloat(avalue); }

  回到dom-geometry的源码,geom.boxModel变量代表当前浏览器中对元素使用的盒式模型,默认为content-box,同时判断了ie浏览器下的情况:

var geom = {
// summary:
// This module defines the core dojo DOM geometry API.
}; // can be either:
// "border-box"
// "content-box" (default)
geom.boxModel = "content-box"; if(has("ie") /*|| has("opera")*/){
// client code may have to adjust if compatMode varies across iframes
geom.boxModel = document.compatMode == "BackCompat" ? "border-box" : "content-box";
}

  接下来的几个函数比较简单、基础,通过getComputedStyle都能直接拿到相应属性:

  getPadExtents():getComputedStyle后得到paddingLeft、paddingRight、paddingTop、paddingBottom

 geom.getPadExtents = function getPadExtents(/*DomNode*/ node, /*Object*/ computedStyle){

         node = dom.byId(node);
var s = computedStyle || style.getComputedStyle(node), px = style.toPixelValue,
l = px(node, s.paddingLeft), t = px(node, s.paddingTop), r = px(node, s.paddingRight), b = px(node, s.paddingBottom);
return {l: l, t: t, r: r, b: b, w: l + r, h: t + b};
};

  getBorderExtents():getComputedStyle后得到borderLeftWidth、borderRightWidth、borderTopWidth、borderBottomWidth;同时如果border-style设置为none,border宽度为零

 geom.getBorderExtents = function getBorderExtents(/*DomNode*/ node, /*Object*/ computedStyle){
node = dom.byId(node);
var px = style.toPixelValue, s = computedStyle || style.getComputedStyle(node),
l = s.borderLeftStyle != none ? px(node, s.borderLeftWidth) : 0,
t = s.borderTopStyle != none ? px(node, s.borderTopWidth) : 0,
r = s.borderRightStyle != none ? px(node, s.borderRightWidth) : 0,
b = s.borderBottomStyle != none ? px(node, s.borderBottomWidth) : 0;
return {l: l, t: t, r: r, b: b, w: l + r, h: t + b};
};

  getPadBorderExtents():通过上两个方法,pad+border

 geom.getPadBorderExtents = function getPadBorderExtents(/*DomNode*/ node, /*Object*/ computedStyle){
node = dom.byId(node);
var s = computedStyle || style.getComputedStyle(node),
p = geom.getPadExtents(node, s),
b = geom.getBorderExtents(node, s);
return {
l: p.l + b.l,
t: p.t + b.t,
r: p.r + b.r,
b: p.b + b.b,
w: p.w + b.w,
h: p.h + b.h
};
};

  getMarginExtents():getComputedStyle后得到marginLeft、marginRight、marginTop、marginBottom

 geom.getMarginExtents = function getMarginExtents(node, computedStyle){
node = dom.byId(node);
var s = computedStyle || style.getComputedStyle(node), px = style.toPixelValue,
l = px(node, s.marginLeft), t = px(node, s.marginTop), r = px(node, s.marginRight), b = px(node, s.marginBottom);
return {l: l, t: t, r: r, b: b, w: l + r, h: t + b};
};

  

  下面的几个函数稍微有点复杂

  getMarginBox()这个方法返回一个对象

{
t: 父元素上内边框到元素上外边距的距离,
l: 父元素左内边框到元素左外边距的距离,
w: 元素左外边距到右外边距的距离,
h: 元素上外边距到下外边距的距离
}

  这个函数中主要用到上文提到的偏移量,正常情况下:

  t = offsetTop,

  l = offsetLeft,

  w = offsetWidth + marginExtents.w,

  h = offsetHeight + marginExtents.h

  在这个函数中有几个兼容性问题:

  1、在firefox中,如果元素的overflow样子的计算值不为visible,那么offsetLeft/offsetTop得到的值是减去borderLeftStyle/borderTopStyle后的值。这应该是firefox的bug,所以我们要对此进行修复。如果getComputedStyle中能够得到left和top那就用这两个属性代替offsetLeft和offsetTop,否则计算parentNode的border宽度,手动加上这部分值

 if(has("mozilla")){
// Mozilla:
// If offsetParent has a computed overflow != visible, the offsetLeft is decreased
// by the parent's border.
// We don't want to compute the parent's style, so instead we examine node's
// computed left/top which is more stable.
var sl = parseFloat(s.left), st = parseFloat(s.top);
if(!isNaN(sl) && !isNaN(st)){
l = sl;
t = st;
}else{
// If child's computed left/top are not parseable as a number (e.g. "auto"), we
// have no choice but to examine the parent's computed style.
if(p && p.style){
pcs = style.getComputedStyle(p);
if(pcs.overflow != "visible"){
l += pcs.borderLeftStyle != none ? px(node, pcs.borderLeftWidth) : 0;
t += pcs.borderTopStyle != none ? px(node, pcs.borderTopWidth) : 0;
}
}
}
}

  2、在IE8和opera中情况正好相反,offsetLeft/offsetTop包含了父元素的边框,这里我们需要把他们减去

 if(has("opera") || (has("ie") == 8 && !has("quirks"))){
// On Opera and IE 8, offsetLeft/Top includes the parent's border
if(p){
pcs = style.getComputedStyle(p);
l -= pcs.borderLeftStyle != none ? px(node, pcs.borderLeftWidth) : 0;
t -= pcs.borderTopStyle != none ? px(node, pcs.borderTopWidth) : 0;
}
}

  真个函数代码如下:

 geom.getMarginBox = function getMarginBox(/*DomNode*/ node, /*Object*/ computedStyle){
node = dom.byId(node);
var s = computedStyle || style.getComputedStyle(node), me = geom.getMarginExtents(node, s),
l = node.offsetLeft - me.l, t = node.offsetTop - me.t, p = node.parentNode, px = style.toPixelValue, pcs;
if(has("mozilla")){
var sl = parseFloat(s.left), st = parseFloat(s.top);
if(!isNaN(sl) && !isNaN(st)){
l = sl;
t = st;
}else{
if(p && p.style){
pcs = style.getComputedStyle(p);
if(pcs.overflow != "visible"){
l += pcs.borderLeftStyle != none ? px(node, pcs.borderLeftWidth) : 0;
t += pcs.borderTopStyle != none ? px(node, pcs.borderTopWidth) : 0;
}
}
}
}else if(has("opera") || (has("ie") == 8 && !has("quirks"))){
if(p){
pcs = style.getComputedStyle(p);
l -= pcs.borderLeftStyle != none ? px(node, pcs.borderLeftWidth) : 0;
t -= pcs.borderTopStyle != none ? px(node, pcs.borderTopWidth) : 0;
}
}
return {l: l, t: t, w: node.offsetWidth + me.w, h: node.offsetHeight + me.h};
};

  

  getContentBox()函数返回如下对象:

{
l: 元素左内边距,
t: 元素上内边距,
w: 元素内容区的宽度,
h: 元素内容区的高度
}

  对象中的w和h与元素的盒式模型无关。以内容区的宽高都有两套方案:clientWidth-padingWidth或者offsetWidth-paddingWidth-borderWidth,下面是函数的源码:

 geom.getContentBox = function getContentBox(node, computedStyle){
// summary:
// Returns an object that encodes the width, height, left and top
// positions of the node's content box, irrespective of the
// current box model.
// node: DOMNode
// computedStyle: Object?
// This parameter accepts computed styles object.
// If this parameter is omitted, the functions will call
// dojo/dom-style.getComputedStyle to get one. It is a better way, calling
// dojo/dom-style.getComputedStyle once, and then pass the reference to this
// computedStyle parameter. Wherever possible, reuse the returned
// object of dojo/dom-style.getComputedStyle(). // clientWidth/Height are important since the automatically account for scrollbars
// fallback to offsetWidth/Height for special cases (see #3378)
node = dom.byId(node);
var s = computedStyle || style.getComputedStyle(node), w = node.clientWidth, h,
pe = geom.getPadExtents(node, s), be = geom.getBorderExtents(node, s);
if(!w){
w = node.offsetWidth;
h = node.offsetHeight;
}else{
h = node.clientHeight;
be.w = be.h = 0;
}
// On Opera, offsetLeft includes the parent's border
if(has("opera")){
pe.l += be.l;
pe.t += be.t;
}
return {l: pe.l, t: pe.t, w: w - pe.w - be.w, h: h - pe.h - be.h};
};

  接下来有三个私有函数setBox、isButtonTag、usersBorderBox。

  setBox忽略盒式模型,直接对元素样式的width、height、left、top进行设置

 function setBox(/*DomNode*/ node, /*Number?*/ l, /*Number?*/ t, /*Number?*/ w, /*Number?*/ h, /*String?*/ u){
// summary:
// sets width/height/left/top in the current (native) box-model
// dimensions. Uses the unit passed in u.
// node:
// DOM Node reference. Id string not supported for performance
// reasons.
// l:
// left offset from parent.
// t:
// top offset from parent.
// w:
// width in current box model.
// h:
// width in current box model.
// u:
// unit measure to use for other measures. Defaults to "px".
u = u || "px";
var s = node.style;
if(!isNaN(l)){
s.left = l + u;
}
if(!isNaN(t)){
s.top = t + u;
}
if(w >= 0){
s.width = w + u;
}
if(h >= 0){
s.height = h + u;
}
}

  isButtonTag函数用来判断元素是否是button按钮,button元素可能是直接的<button>标签,也可能是<input type="button">,所以要对着两方面进行判断

 function isButtonTag(/*DomNode*/ node){
// summary:
// True if the node is BUTTON or INPUT.type="button".
return node.tagName.toLowerCase() == "button" ||
node.tagName.toLowerCase() == "input" && (node.getAttribute("type") || "").toLowerCase() == "button"; // boolean
}

  usersBorderBox判断元素的盒式模型是否为border-box,三个方面:geom的boxModel是否为border-box、元素是否为table元素,元素是否为button元素

 function usesBorderBox(/*DomNode*/ node){
// summary:
// True if the node uses border-box layout. // We could test the computed style of node to see if a particular box
// has been specified, but there are details and we choose not to bother. // TABLE and BUTTON (and INPUT type=button) are always border-box by default.
// If you have assigned a different box to either one via CSS then
// box functions will break. return geom.boxModel == "border-box" || node.tagName.toLowerCase() == "table" || isButtonTag(node); // boolean
}

  setContentSize方法,设置元素内容区的大小。如果元素盒式模式是border-box,则需要在参数传入的width基础上加上padding与border的宽度,否则直接设置width、height样式。

 geom.setContentSize = function setContentSize(/*DomNode*/ node, /*Object*/ box, /*Object*/ computedStyle){
// summary:
// Sets the size of the node's contents, irrespective of margins,
// padding, or borders.
// node: DOMNode
// box: Object
// hash with optional "w", and "h" properties for "width", and "height"
// respectively. All specified properties should have numeric values in whole pixels.
// computedStyle: Object?
// This parameter accepts computed styles object.
// If this parameter is omitted, the functions will call
// dojo/dom-style.getComputedStyle to get one. It is a better way, calling
// dojo/dom-style.getComputedStyle once, and then pass the reference to this
// computedStyle parameter. Wherever possible, reuse the returned
// object of dojo/dom-style.getComputedStyle(). node = dom.byId(node);
var w = box.w, h = box.h;
if(usesBorderBox(node)){
var pb = geom.getPadBorderExtents(node, computedStyle);
if(w >= 0){
w += pb.w;
}
if(h >= 0){
h += pb.h;
}
}
setBox(node, NaN, NaN, w, h);
};

  setMarginBox方法,设置marginBox的宽度。该方法中不去判断元素的盒式模型,width = w-padding - border -margin。通过这种方式直接设置元素的width或height属性。这里涉及的兼容性问题,主要对于低版本浏览器,所以不去分析他。

 geom.setMarginBox = function setMarginBox(/*DomNode*/ node, /*Object*/ box, /*Object*/ computedStyle){
// summary:
// sets the size of the node's margin box and placement
// (left/top), irrespective of box model. Think of it as a
// passthrough to setBox that handles box-model vagaries for
// you.
// node: DOMNode
// box: Object
// hash with optional "l", "t", "w", and "h" properties for "left", "right", "width", and "height"
// respectively. All specified properties should have numeric values in whole pixels.
// computedStyle: Object?
// This parameter accepts computed styles object.
// If this parameter is omitted, the functions will call
// dojo/dom-style.getComputedStyle to get one. It is a better way, calling
// dojo/dom-style.getComputedStyle once, and then pass the reference to this
// computedStyle parameter. Wherever possible, reuse the returned
// object of dojo/dom-style.getComputedStyle(). node = dom.byId(node);
var s = computedStyle || style.getComputedStyle(node), w = box.w, h = box.h,
// Some elements have special padding, margin, and box-model settings.
// To use box functions you may need to set padding, margin explicitly.
// Controlling box-model is harder, in a pinch you might set dojo/dom-geometry.boxModel.
pb = usesBorderBox(node) ? nilExtents : geom.getPadBorderExtents(node, s),
mb = geom.getMarginExtents(node, s);
if(has("webkit")){
// on Safari (3.1.2), button nodes with no explicit size have a default margin
// setting an explicit size eliminates the margin.
// We have to swizzle the width to get correct margin reading.
if(isButtonTag(node)){
var ns = node.style;
if(w >= 0 && !ns.width){
ns.width = "4px";
}
if(h >= 0 && !ns.height){
ns.height = "4px";
}
}
}
if(w >= 0){
w = Math.max(w - pb.w - mb.w, 0);
}
if(h >= 0){
h = Math.max(h - pb.h - mb.h, 0);
}
setBox(node, box.l, box.t, w, h);
};

  position()方法,主要使用node.getBoundingClientRect() ,这个方法得到left、right、top、bottom。在老版本ie下,这个方法的基准点并不是从(0,0)开始计算的,而是以(2,2)位基准点。所以ie中这个方法得到的位置信息比实际位置多了两个像素,我们要把这两个像素减掉。基准点位置偏移两个像素,所以dcument.documentElement即<html>标签的位置也不是0;所以我们可以利用document.documentElement.getBoundingClientRect().left/top得到偏移量。减去偏移量就得到了真正的位置。(偏移量问题在IE9已经修复了,而IE8标准模式是没有这个问题,所以具体获取偏移量的细节不讨论)

 geom.position = function(/*DomNode*/ node, /*Boolean?*/ includeScroll){
// summary:
// Gets the position and size of the passed element relative to
// the viewport (if includeScroll==false), or relative to the
// document root (if includeScroll==true).
//
// description:
// Returns an object of the form:
// `{ x: 100, y: 300, w: 20, h: 15 }`.
// If includeScroll==true, the x and y values will include any
// document offsets that may affect the position relative to the
// viewport.
// Uses the border-box model (inclusive of border and padding but
// not margin). Does not act as a setter.
// node: DOMNode|String
// includeScroll: Boolean?
// returns: Object node = dom.byId(node);
var db = win.body(node.ownerDocument),
ret = node.getBoundingClientRect();
ret = {x: ret.left, y: ret.top, w: ret.right - ret.left, h: ret.bottom - ret.top}; if(has("ie") < 9){
// On IE<9 there's a 2px offset that we need to adjust for, see dojo.getIeDocumentElementOffset()
var offset = geom.getIeDocumentElementOffset(node.ownerDocument); // fixes the position in IE, quirks mode
ret.x -= offset.x + (has("quirks") ? db.clientLeft + db.offsetLeft : 0);
ret.y -= offset.y + (has("quirks") ? db.clientTop + db.offsetTop : 0);
} // account for document scrolling
// if offsetParent is used, ret value already includes scroll position
// so we may have to actually remove that value if !includeScroll
if(includeScroll){
var scroll = geom.docScroll(node.ownerDocument);
ret.x += scroll.x;
ret.y += scroll.y;
} return ret; // Object
};

  normalizeEvent()方法主要针对鼠标位置信息layerX/layerY、pageX/pageY做修正;前者利用ie中的offsetX/offsetY即可,后者利用clientX+documentElement/body.scrollLeft - offset和clientY+documentElement/body.scrollTop - offset,offset即是上文提到的在ie中偏移量。

geom.normalizeEvent = function(event){
// summary:
// Normalizes the geometry of a DOM event, normalizing the pageX, pageY,
// offsetX, offsetY, layerX, and layerX properties
// event: Object
if(!("layerX" in event)){
event.layerX = event.offsetX;
event.layerY = event.offsetY;
}
if(!has("dom-addeventlistener")){
// old IE version
// FIXME: scroll position query is duped from dojo/_base/html to
// avoid dependency on that entire module. Now that HTML is in
// Base, we should convert back to something similar there.
var se = event.target;
var doc = (se && se.ownerDocument) || document;
// DO NOT replace the following to use dojo/_base/window.body(), in IE, document.documentElement should be used
// here rather than document.body
var docBody = has("quirks") ? doc.body : doc.documentElement;
var offset = geom.getIeDocumentElementOffset(doc);
event.pageX = event.clientX + geom.fixIeBiDiScrollLeft(docBody.scrollLeft || 0, doc) - offset.x;
event.pageY = event.clientY + (docBody.scrollTop || 0) - offset.y;
}
};

  一个周的学习研究结束,如果您觉得这篇文章对您有帮助,请不吝点击下方推荐