简体   繁体   English

在Angularjs指令中从滚动容器div的顶部获取元素位置

[英]Getting element position from the top of scrolled container div in Angularjs directive

I have a simple structure div named scrollContainer with overflow-y:scroll rule and an inner larger div called inner . 我有一个名为scrollContainer的简单结构div, scrollContainer具有overflow-y:scroll规则和一个内部较大的div,名为inner

In the inner div I have some texts and an input. 在内部div中,我有一些文本和输入。 On the input I have an attribute directive called getPosition applied, which should return on scroll event the exact position of the input relative to the top of scrollContainer . 在输入上,我应用了一个名为getPosition的属性指令,该指令应在滚动事件中返回输入相对于scrollContainer顶部的确切位置。

This is what I need: 这就是我需要的: 在此处输入图片说明

Here is the sample angular app: https://codepen.io/neptune01/pen/vapmLQ 这是示例角度应用程序: https : //codepen.io/neptune01/pen/vapmLQ

As you can see, tried with offsetTop and other dom properties, but I couldn't find anything that would result what I need. 如您所见,尝试过使用offsetTop和其他dom属性,但是我找不到任何能满足我需要的东西。

I would recommend using a combination of getBoundingClientRect() and the current scroll position to accomplish this like so: 我建议结合使用getBoundingClientRect()和当前滚动位置来完成此操作,如下所示:

let outer = document.getElementById('scrollContainer');
let inner = document.getElementById('inner');

let outerTop = outer.getBoundingClientRect().top + (window.scrollY || window.pageYOffset);
let innerTop = inner.getBoundingClientRect().top + (window.scrollY || window.pageYOffset);

let difference = innerTop - outerTop;

The reason you wouldn't just subtract outer top from inner top in the first place and ignore the scroll position is because on the off chance that you are scrolling while the calculations take place you could throw off the offset, as getBoundingClientRect() only takes into account the distance from the edge of your view to the element, while the scrollY shows the distance from the edge of your view to the top of the document. 您不只是从内部顶部减去外部顶部而忽略滚动位置的原因是因为在进行计算的同时滚动的可能性很小,因为getBoundingClientRect()仅占用了偏移量考虑从视图边缘到元素的距离,而scrollY显示从视图边缘到文档顶部的距离。

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

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