jQuery:以整数格式获取元素的像素位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4652546/
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
jQuery: Getting px position of an element in Integer format
提问by kylex
This code works in FF, but not in IE:
此代码适用于 FF,但不适用于 IE:
parseInt($('.scroller').css('left');
In FF it returns 0px;
在 FF 中它返回 0px;
In IE it returns NaN
.
在 IE 中它返回NaN
.
What's a good way to get a pixel position of an element?
获取元素像素位置的好方法是什么?
<div class="holder">
<div class="scroller">
</div>
</div>
回答by lonesomeday
Use offset
:
使用offset
:
$('.scroller').offset().left;
offset()
returns an object containing the properties left
and top
, which are the position values relative to the document in pixels.
offset()
返回一个包含属性left
和的对象top
,它们是相对于文档的位置值(以像素为单位)。
If you want the position relative to the parent element, use position
instead.
如果您想要相对于父元素的位置,请position
改用。
回答by konrad.kruczynski
It would be however always relative to document, therefore position() (relative to parent, i.e. holder) would sometimes be rather accurate and sometimes none of them.
然而,它总是相对于文档,因此 position() (相对于父级,即持有者)有时会相当准确,有时它们都不是。