javascript 如何获取可滚动div内对象的相对位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14563293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:59:29  来源:igfitidea点击:

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

javascripthtml

提问by Ashraf Bashir

enter image description here

在此处输入图片说明

I have a scrollable div, the one on the left in the above image.
In this div there exist many elements, lets focus on one of them (highlighted in grey) and call it A.

我有一个可滚动的 div,即上图中左侧的那个。
在这个 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.
i.e. taking into consideration:

我怎样才能找到 X 的值(绿色),同时页面上当前有左边的 div。
即考虑到:

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

i.e. How to get the relative y coordinate of an element inside a scrollable div ? in simple words: how to calculate x via javascript ?

即如何获取可滚动 div 中元素的相对 y 坐标?简单来说:如何通过javascript计算x?

回答by RodolpheChe

Try this :

试试这个 :

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