I have a simple structure div named scrollContainer
with overflow-y:scroll
rule and an inner larger div called inner
.
In the inner div I have some texts and an input. 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
.
Here is the sample angular app: 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.
I would recommend using a combination of getBoundingClientRect() and the current scroll position to accomplish this like so:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.