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

javascript - Calculate element-position - Stack Overflow

programmeradmin0浏览0评论

I would like to calculate the vertical position of a <div> with jQuery.

How would I do this?

Here's an illustration describing what I mean:

I would like to calculate the vertical position of a <div> with jQuery.

How would I do this?

Here's an illustration describing what I mean:

Share Improve this question edited Apr 21, 2011 at 15:46 Blender 298k55 gold badges458 silver badges510 bronze badges asked Apr 21, 2011 at 15:44 PatrikPatrik 1,1295 gold badges18 silver badges37 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 10

I think you're looking for its offset from the top of the page, right?

$('#div').scrollTop();

If that's not it, maybe the offset would work:

$('#div').offset().top;

Okay, now that it needs to be relative to the parent, try this:

$('#div').position().top;
$('#innerDiv').position()

Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

jQuery Manual for position()

I think you're looking for

$(elem).offset();

http://api.jquery.com/offset/

If you want it relative to it's container, then you're after http://api.jquery.com/position/ instead.

jQuery has several functions to help you find the offset that you are looking for.

var element = $("#your_element");

// Get the current coordinates of the first element in the set of matched elements, relative to the document.
element.offset() 

// Get the closest ancestor element that is positioned.
element.offsetParent() 

// Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.
element.position()

// Get the current horizontal position of the scroll bar for the first element in the set of matched elements.
element.scrollLeft()

// Get the current vertical position of the scroll bar for the first element in the set of matched elements.
element.scrollTop()

For more information read about these at the jQuery offset api page.

I reckon that the jQuery API "position()" isn't what you are looking for, since it is defined as "the current position of an element relative to the offset parent" (basically it corresponds to element.offsetTop)

Therefore if you want the top position of the element relative to its parent (not necessary the offset parent), use this instead:

var top = (element.parentNode == element.offsetParent) ? element.offsetTop : element.offsetTop - element.parentNode.offsetTop;
发布评论

评论列表(0)

  1. 暂无评论