关于获取控件的offset

📅 2026/8/3 19:08:33
关于获取控件的offset
问题通过点击一控件在控件的下面显示一个浮动层通常的做法是获取此控件的offset值再计算出浮动层的topleft等css属性的值赋值即可。那么下面就看一下如何获取控件的offset值。纯JS的实现首先想到的是这样的一段js。document.getElementById(divFloat).style.topdocument.getElementById(Button).offsetLeft25;发现需要添加值单位那么就修改成下面这样子。document.getElementById(divFloat).style.top(document.getElementById(Button).offsetLeft25)px;用IETester和FireFox再测试下IE6下都可以如以前一样写出的纯js的方法无情地被FireFox鄙视了获取的值不正确。网上再查了下发现应该这样写通过循环层层向上计算最后得到准确的offset值。functiongetOffsetLeft(o){varleft0;varoffsetParento;while(offsetParent!nulloffsetParent!document.body){leftoffsetParent.offsetLeft;offsetParentoffsetParent.offsetParent;}returnleft;}jQuery的实现再细一步去查相关问题时发现jQuery中已经包含了实现此功能的函数offset()很好地兼容了各浏览器。$(#Button).offset().left还有一个函数是position()两者详细的对比分析在这里深入剖析Jquery中的offset()和position()下载源码后发现jQuery是这样实现的jQuery.fn.extend({position:function() {if(!this[0] ) {returnnull;}varelemthis[0],//Get *real* offsetParentoffsetParentthis.offsetParent(),//Get correct offsetsoffsetthis.offset(),parentOffset/^body|html$/i.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 0offset.top-parseFloat( jQuery.curCSS(elem,marginTop,true) )||0;offset.left-parseFloat( jQuery.curCSS(elem,marginLeft,true) )||0;//Add offsetParent bordersparentOffset.topparseFloat( jQuery.curCSS(offsetParent[0],borderTopWidth,true) )||0;parentOffset.leftparseFloat( jQuery.curCSS(offsetParent[0],borderLeftWidth,true) )||0;//Subtract the two offsetsreturn{top: offset.top-parentOffset.top,left: offset.left-parentOffset.left};},offsetParent:function() {returnthis.map(function() {varoffsetParentthis.offsetParent||document.body;while( offsetParent(!/^body|html$/i.test(offsetParent.nodeName)jQuery.css(offsetParent,position)static) ) {offsetParentoffsetParent.offsetParent;}returnoffsetParent;});}});没有太理解先贴在这里了