问题
How to get xy coordinates of child element from parent element, and not the(body)? How to get x value from DIV B to DIV A, so when window resizes, the values stay true???

var startPos = $("#divB").position();
$("#divB").draggable({
containment: 'parent',
stop: function(event, ui) {
var stopPos = $(this).position();
$("#firstInput").val((stopPos.left - startPos.left));
}
});
Is there a method to get this values directly and not from xy coordinates of whole screen?
回答1:
To get the offset of a child element relative to its' parent use position()
:
$("#child").position().left;
$("#child").position().top;
The caveat on this being that the parent must NOT be position: static
for this to work. If the parent is static, jQuery will just return the offset()
- which I assume is what is happening in your code.
static
is the default for most block elements, so you'll need to set position
to fixed
, absolute
or relative
on the parent in your CSS.
来源:https://stackoverflow.com/questions/8446179/how-to-get-xy-coordinates-of-child-element-from-parent-element-in-jquery