javascript Getting distance of child element from top-left corner of Parent element
Is there a way to get the offset of a ChildElement from a given parent element?
for example if a DIV in contained within a parent DIV with id "xyz"
is there a 开发者_开发知识库way to say
parent = $("xyz");
child = $("abc");
child.offset(parent);
Thank you
A convenient method is Element.getPositionedOffset()
, but only when the parent element has a position
style property.
var offset = $('abc').positionedOffset();
offset.left;
offset.top;
Otherwise it takes a little more work:
var parent = $('xyz',
child = $('abc'),
offset = child.viewportOffset().relativeTo(parent.viewportOffset());
The advantage here is the two elements need not be directly related, any pair of elements on the page can do.
精彩评论