如何从jquery中的父元素获取子元素的xy坐标?
如何从父元素而不是(body)获取子元素的xy坐标?如何从DIV B到DIV A获取x值,所以当窗口调整大小时,值保持为真??
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));
}
});
是否有一种方法可以直接获取此值,而不是从整个屏幕的xy坐标中获取?
Is there a method to get this values directly and not from xy coordinates of whole screen?
要获取子元素相对于其父元素的偏移量,请使用position()
:
To get the offset of a child element relative to its' parent use position()
:
$("#child").position().left;
$("#child").position().top;
对此的警告是,父母必须不必须为position: static
才能起作用.如果父对象是静态的,则jQuery将仅返回offset()
-我认为这是您的代码中发生的事情.
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
是大多数块元素的默认设置,因此您需要在CSS的父级上将position
设置为fixed
,absolute
或relative
.
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.