How to get xy coordinates of child element from parent element in jquery?

痞子三分冷 提交于 2019-12-11 05:26:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!