admin管理员组文章数量:1391989
I have a <li>
which is nested inside a containing <ul>
, what I would like is to calculate the offset. But have the top-left corner of the <ul>
be 0, 0
.
So my HTML is:
<div style="margin: 0 auto; width: 760px; height: 760px; overflow: hidden;">
<ul style="width: 2000px; height: 2000px; min-height: 2000px; position: relative;">
<li style="position: relative; width: 40px; height: 40px;"></li>
</ul>
</div>
And my current jQuery is:
thePos = $('ul li').offset();
alert('X = '+thePos.left+', Y = 'thePos.top);
However, this is returning offsets that are not 0, 0
. I guess it is calculating the offset relative to the edge of the document instead of the parent container.
How can I get around this?
Thanking you.
note: position()
doesn't retrieve the right numbers either :(
I have a <li>
which is nested inside a containing <ul>
, what I would like is to calculate the offset. But have the top-left corner of the <ul>
be 0, 0
.
So my HTML is:
<div style="margin: 0 auto; width: 760px; height: 760px; overflow: hidden;">
<ul style="width: 2000px; height: 2000px; min-height: 2000px; position: relative;">
<li style="position: relative; width: 40px; height: 40px;"></li>
</ul>
</div>
And my current jQuery is:
thePos = $('ul li').offset();
alert('X = '+thePos.left+', Y = 'thePos.top);
However, this is returning offsets that are not 0, 0
. I guess it is calculating the offset relative to the edge of the document instead of the parent container.
How can I get around this?
Thanking you.
note: position()
doesn't retrieve the right numbers either :(
2 Answers
Reset to default 8Try using position()
instead of offset()
.
From the jQuery docs:
The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent.
I fixed this by setting:
thePosX = $('ul li').css('left');
thePosY = $('ul li').css('top');
Instead of:
thePos = $('ul li').css('left');
本文标签: javascriptHow to calculate the offset() of an ltligt relative to its parent containerStack Overflow
版权声明:本文标题:javascript - How to calculate the offset() of an <li> relative to its parent container - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744589196a2614380.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论