offsetTop vs. jQuery.offset().top
我已阅读
我想做的是获取相对于元素左上角单击元素的位置的坐标。
问题是
这个小提琴展示了这个问题。 如果单击底部图像,则
我想认为
这是jQuery API Doc关于
Get the current coordinates of the first element, or set the
coordinates of every element, in the set of matched elements, relative
to the document.
这是MDN Web API关于
offsetTop returns the distance of the current element relative to the
top of the offsetParent node
这是jQuery v.1.11
1 2 3 4 5 6 7 8 9 10 11 | var box = { top: 0, left: 0 }; // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; |
-
pageYOffset 直观地说页面滚动了多少 -
docElem.scrollTop 是备用fo <9(jQuery 2不支持BTW) -
docElem.clientTop 是元素(在本例中为文档)顶部边框的宽度 -
elem.getBoundingClientRect() 获取相对于 document s>视口的坐标(请参见注释)。它可能返回分数值,因此这是您的错误的来源。缩放页面时,它也可能会导致i <8的错误。为了避免分数值,请尝试迭代计算位置
结论
-
如果要相对于父节点的坐标,请使用
element.offsetTop 。如果要考虑父滚动,请添加element.scrollTop 。 (如果您是该库的粉丝,请使用jQuery .position()) -
如果要相对于视口的坐标,请使用
element.getBoundingClientRect().top 。如果要考虑文档滚动,请添加window.pageYOffset 。如果文档没有边框(通常没有边框),则无需减去文档的clientTop ,因此您具有相对于文档的位置 -
如果您不将元素边框视为元素的一部分,则减去
element.clientTop
我认为您说的是人们不能点击半个像素是正确的,所以就我个人而言,我将使用四舍五入的jQuery偏移量...
试试这个?wyn>>parseInt(jQuery.offset().top, 1e>
使?wyn>de>作为度量单位
我还假设,?wyn/code>不?wy时?wynt可能不是整数,但这取决于浏览器如何处理缩放。
您可以使?wyn>>parseInt(jQuery.offsp)在所有浏览器中始终使用Integer(原始nt)值。