如何从jquery中的父元素获取子元素的xy坐标? [英] How to get xy coordinates of child element from parent element in jquery?

查看:245
本文介绍了如何从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设置为fixedabsoluterelative.

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.

这篇关于如何从jquery中的父元素获取子元素的xy坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆