开发者

Calculate element-position

开发者 https://www.devze.com 2023-02-28 11:34 出处:网络
I would like to calculate the vertic开发者_StackOverflow中文版al position of a <div> with jQuery.

I would like to calculate the vertic开发者_StackOverflow中文版al position of a <div> with jQuery.

How would I do this?

Here's an illustration describing what I mean:

Calculate element-position


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

精彩评论

暂无评论...
验证码 换一张
取 消