简体   繁体   English

如何在可滚动的div中获取对象的相对位置?

[英]How to get the relative position of an object inside a scrollable div?

在此输入图像描述

I have a scrollable div, the one on the left in the above image. 我有一个可滚动的div,上图中左边的那个。
In this div there exist many elements, lets focus on one of them (highlighted in grey) and call it A. 在这个div中存在许多元素,让我们专注于其中一个(以灰色突出显示)并将其称为A.

The right image is a representation of the div with the full size (without scroll or width setting) where A is placed without scrolling. 右图是具有完整尺寸(没有滚动或宽度设置)的div的表示,其中A放置而不滚动。

How may I find the value of X (in green), while having the left div currently on the page. 如何在页面上显示左侧div时,如何找到X的值(绿色)。
ie taking into consideration: 即考虑到:

  1. The div on page is already resized 页面上的div已经调整大小
  2. The div on page is scrollable (and has been scrolled) 页面上的div是可滚动的(并已滚动)
  3. I want x not y ! 我想x不是你!

ie How to get the relative y coordinate of an element inside a scrollable div ? 即如何获得可滚动div内元素的相对y坐标? in simple words: how to calculate x via javascript ? 用简单的话说:如何通过javascript计算x?

Try this : 试试这个 :

var elementTop = document.getElementById('yourElementId').offsetTop;
var divTop = document.getElementById('yourDivId').offsetTop;
var elementRelativeTop = elementTop - divTop;

You need to specify the parent's div position property to be relative and then use the position() method (if you are using jquery). 您需要将父级的div位置属性指定为相对属性,然后使用position()方法(如果您使用的是jquery)。

Check this: http://jsfiddle.net/V9rGG/ 检查一下: http//jsfiddle.net/V9rGG/

Try to remove the position: relative and see what happens. 尝试删除position: relative ,看看会发生什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM