jQuery中offset()和position()方法

通过源码来学习offset和position方法才能更深入理解其实现
jQuery的offset()方法

获取匹配元素在当前视口的相对偏移。
返回的对象包含两个整形属性:top 和 left。此方法只对可见元素有效。

jQuery的position()方法

获取匹配元素相对父元素的偏移。
返回的对象包含两个整形属性:top 和 left。此方法只对可见元素有效。

jQuery1.4源码:

var rtable = /^t(?:able|d|h)$/i,
rroot = /^(?:body|html)$/i;

if ( "getBoundingClientRect" in document.documentElement ) {
jQuery.fn.offset = function( options ) {
var elem = this[0], box;

if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}

if ( !elem || !elem.ownerDocument ) {
return null;
}

if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}

try {
box = elem.getBoundingClientRect();
} catch(e) {}

var doc = elem.ownerDocument,
docElem = doc.documentElement;

// Make sure we're not dealing with a disconnected DOM node
if ( !box || !jQuery.contains( docElem, elem ) ) {
return box || { top: 0, left: 0 };
}

var body = doc.body,
win = getWindow(doc),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = (win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ),
scrollLeft = (win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft),
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;

return { top: top, left: left };
};

} else {
jQuery.fn.offset = function( options ) {
var elem = this[0];

if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}

if ( !elem || !elem.ownerDocument ) {
return null;
}

if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}

jQuery.offset.initialize();

var computedStyle,
offsetParent = elem.offsetParent,
prevOffsetParent = elem,
doc = elem.ownerDocument,
docElem = doc.documentElement,
body = doc.body,
defaultView = doc.defaultView,
prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
top = elem.offsetTop,
left = elem.offsetLeft;

while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
break;
}

computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
top -= elem.scrollTop;
left -= elem.scrollLeft;

if ( elem === offsetParent ) {
top += elem.offsetTop;
left += elem.offsetLeft;

if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}

prevOffsetParent = offsetParent;
offsetParent = elem.offsetParent;
}

if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}

prevComputedStyle = computedStyle;
}

if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
top += body.offsetTop;
left += body.offsetLeft;
}

if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
top += Math.max( docElem.scrollTop, body.scrollTop );
left += Math.max( docElem.scrollLeft, body.scrollLeft );
}

return { top: top, left: left };
};
}

jQuery.offset = {
initialize: function() {
var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0,
html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";

jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } );

container.innerHTML = html;
body.insertBefore( container, body.firstChild );
innerDiv = container.firstChild;
checkDiv = innerDiv.firstChild;
td = innerDiv.nextSibling.firstChild.firstChild;

this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
this.doesAddBorderForTableAndCells = (td.offsetTop === 5);

checkDiv.style.position = "fixed";
checkDiv.style.top = "20px";

// safari subtracts parent border width here which is 5px
this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15);
checkDiv.style.position = checkDiv.style.top = "";

innerDiv.style.overflow = "hidden";
innerDiv.style.position = "relative";

this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);

this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop);

body.removeChild( container );
body = container = innerDiv = checkDiv = table = td = null;
jQuery.offset.initialize = jQuery.noop;
},

bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;

jQuery.offset.initialize();

if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}

return { top: top, left: left };
},

setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );

// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}

var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = (position === "absolute" && jQuery.inArray('auto', [curCSSTop, curCSSLeft]) > -1),
props = {}, curPosition = {}, curTop, curLeft;

// need to be able to calculate position if either top or left is auto and position is absolute
if ( calculatePosition ) {
curPosition = curElem.position();
}

curTop = calculatePosition ? curPosition.top : parseInt( curCSSTop, 10 ) || 0;
curLeft = calculatePosition ? curPosition.left : parseInt( curCSSLeft, 10 ) || 0;

if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}

if (options.top != null) {
props.top = (options.top - curOffset.top) + curTop;
}
if (options.left != null) {
props.left = (options.left - curOffset.left) + curLeft;
}

if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};


jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return null;
}

var elem = this[0],

// Get *real* offsetParent
offsetParent = this.offsetParent(),

// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();

// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;

// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;

// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},

offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent;
});
}
});

应用场景:
1: 使用position()方法时事实上是把该元素当绝对定位来处理,获取的是该元素相当于最近的一个拥有绝对或者相对定位的父元素的偏移位置
2: 使用position()方法时如果其所有的父元素都为默认定位(static)方式,则其处理方式和offset()一样,是当前窗口的相对偏移
3: 使用offset()方法不管该元素如何定位,也不管其父元素如何定位,都是获取的该元素相对于当前视口的偏移

参考:
[url]http://www.cnblogs.com/believe3301/archive/2008/07/19/1246806.html[/url]
[url]http://www.js8.in/602.html[/url]
[url]http://article.qmecms.com/frontend/javascript/2010/07/18/jQuery,source,code,analysis,10,jquery,position-297.html[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值