Javascript offsetTop 与 jQuery.offset().top

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6777506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:08:54  来源:igfitidea点击:

offsetTop vs. jQuery.offset().top

javascriptjqueryoffset

提问by Explosion Pills

I have read that offsetLeftand offsetTopdo not work properly in all browsers. jQuery.offset()is supposed to provide an abstraction for this to provide the correct value xbrowser.

我已阅读该内容offsetLeftoffsetTop但并非在所有浏览器中都能正常工作。 jQuery.offset()应该为此提供一个抽象以提供正确的值 xbrowser。

What I am trying to do is get the coordinates of where an element was clicked relative to the top-left of the element.

我想要做的是获取相对于元素左上角的元素点击位置的坐标。

Problem is that jQuery.offset().topis actually giving me a decimal value in FFX 3.6 (in IE and Chrome, the two values match).

问题是jQuery.offset().top实际上在 FFX 3.6 中给了我一个十进制值(在 IE 和 Chrome 中,这两个值匹配)。

This fiddleexhibits the issue. If you click the bottom image, jQuery.offset().topreturns 327.5, but offsetTopreturns 328.

这个小提琴展示了这个问题。如果单击底部图像,则jQuery.offset().top返回 327.5,但offsetTop返回 328。

I would like to think that offset()is returning the correct value and I should use it because it will work across browsers. However, people obviously cannot click decimals of pixels. Is the proper way to determine the true offset to Math.round()the offset that jQuery is returning? Should I use offsetTopinstead, or some other method entirely?

我想认为这offset()是返回正确的值,我应该使用它,因为它可以跨浏览器工作。但是,人们显然无法点击像素的小数点。确定Math.round()jQuery 返回的偏移量的真实偏移量的正确方法是什么?我应该offsetTop改用,还是完全使用其他方法?

采纳答案by ChristopheCVB

I think you are right by saying that people cannot click half pixels, so personally, I would use rounded jQuery offset...

我认为你说人们不能点击半像素是对的,所以就个人而言,我会使用四舍五入的 jQuery 偏移量......

回答by Jan Turoň

This is what jQuery API Docsays about .offset():

这就是jQuery API Doc所说的.offset()

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.

获取第一个元素的当前坐标,或设置匹配元素集中每个元素相对于文档的坐标。

This is what MDN Web APIsays about .offsetTop:

这就是MDN Web API所说的.offsetTop

offsetTop returns the distance of the current element relative to the top of the offsetParent node

offsetTop 返回当前元素相对于offsetParent 节点顶部的距离

This is what jQuery v.1.11 .offset()basically do when getting the coords:

这是 jQuery v.1.11.offset()在获取坐标时的基本操作:

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 )
};
  • pageYOffsetintuitively says how much was the page scrolled
  • docElem.scrollTopis the fallback for IE<9 (which are BTW unsupported in jQuery 2)
  • docElem.clientTopis the width of the top border of an element (the document in this case)
  • elem.getBoundingClientRect()gets the coords relative to the documentviewport(see comments). It may return fraction values, so this is the source of your bug. It also may cause a bug in IE<8when the page is zoomed. To avoid fraction values, try to calculate the position iteratively
  • pageYOffset直观地说明页面滚动了多少
  • docElem.scrollTop是 IE<9 的后备(顺便说一句,jQuery 2 不支持)
  • docElem.clientTop是元素上边框的宽度(在这种情况下是文档)
  • elem.getBoundingClientRect()获取相对于文档视口的坐标(见评论)。它可能会返回分数值,因此这是您的错误的来源。当页面缩放时,它也可能导致 IE<8 中的错误。为避免分数值,请尝试迭代计算位置

Conclusion

结论

  • If you want coords relative to the parent node, use element.offsetTop. Add element.scrollTopif you want to take the parent scrolling into account. (or use jQuery .position()if you are fan of that library)
  • If you want coords relative to the viewportuse element.getBoundingClientRect().top. Add window.pageYOffsetif you want to take the document scrolling into account. You don't need to subtract document's clientTopif the document has no border (usually it doesn't), so you have position relative to the document
  • Subtract element.clientTopif you don't consider the element border as the part of the element
  • 如果您想要相对于父节点的坐标,请使用element.offsetTop. element.scrollTop如果要考虑父滚动,请添加。(或者使用 jQuery .position()如果你是那个库的粉丝)
  • 如果您想要相对于视口的坐标,请使用element.getBoundingClientRect().top. window.pageYOffset如果要考虑文档滚动,请添加。clientTop如果文档没有边框(通常没有),则不需要减去文档,因此您具有相对于文档的位置
  • element.clientTop如果不将元素边框视为元素的一部分,则减去

回答by Steve Chan

Try this: parseInt(jQuery.offset().top, 10)

尝试这个: parseInt(jQuery.offset().top, 10)

回答by Emyr

It is possible that the offsetcould be a non-integer, using emas the measurement unit, relative font-sizesin %.

可能offset是非整数,em用作测量单位,相font-sizes对于%

I also theorise that the offsetmight not be a whole number when the zoomisn't 100%but that depends how the browser handles scaling.

我还推测,offsetzoom不是时,可能不是整数,100%但这取决于浏览器如何处理缩放。

回答by ShankarSangoli

You can use parseInt(jQuery.offset().top)to always use the Integer (primitive - int) value across all browsers.

您可以使用parseInt(jQuery.offset().top)始终int在所有浏览器中使用整数(原始 - )值。