最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to calculate the offset() of an <li> relative to its parent container - Stack Overflow

programmeradmin2浏览0评论

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 :(

Share Improve this question edited Aug 6, 2010 at 11:24 ЯegDwight 25.3k10 gold badges47 silver badges52 bronze badges asked Aug 6, 2010 at 9:38 Barrie ReaderBarrie Reader 10.7k11 gold badges77 silver badges141 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

Try 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');
发布评论

评论列表(0)

  1. 暂无评论