我读过offsetLeft
and offsetTop
不能在所有浏览器中正常工作。jQuery.offset()
应该为此提供一个抽象,以提供正确的值 xbrowser.
我想要做的是获取元素被单击的位置相对于元素左上角的坐标。
问题是jQuery.offset().top
实际上在 FFX 3.6 中给了我一个十进制值(在 IE 和 Chrome 中,这两个值匹配)。
这把小提琴展示了这个问题。如果你点击底部的图片,jQuery.offset().top
返回 327.5,但是offsetTop
返回 328。
我想offset()
返回正确的值,我应该使用它,因为它可以跨浏览器工作。然而,人们显然无法点击像素的小数点。是确定真实偏移量的正确方法Math.round()
jQuery 返回的偏移量?我应该使用offsetTop
相反,或者完全是其他方法?
这是什么jQuery API 文档说关于.offset()
:
获取第一个元素的当前坐标,或设置
匹配元素集中每个元素的相对坐标
到document.
这是什么MDN 网络 API说关于.offsetTop
:
offsetTop 返回当前元素相对于当前元素的距离
的顶部偏移父节点
这就是 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 )
};
-
pageYOffset
直观地说页面滚动了多少
-
docElem.scrollTop
是 IE
-
docElem.clientTop
是元素(本例中为文档)上边框的宽度
-
elem.getBoundingClientRect()
gets the coords relative to the document viewport (see comments). It may return fraction values, so this is the source of your bug. It also may cause a bug in IE<8 when the page is zoomed. To avoid fraction values, try to calculate the position iteratively
结论
- 如果你想要相对于父节点, use
element.offsetTop
. Add element.scrollTop
如果你想考虑父滚动。 (或使用 jQuery。位置()如果你是那个图书馆的粉丝)
- 如果你想要相对于viewport use
element.getBoundingClientRect().top
. Add window.pageYOffset
如果你想考虑文档滚动。您不需要减去文档的clientTop
如果文档没有边框(通常没有),那么您就有相对于document
- 减去
element.clientTop
如果您不将元素边框视为元素的一部分
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)