簡體   English   中英

在Angularjs指令中從滾動容器div的頂部獲取元素位置

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

我有一個名為scrollContainer的簡單結構div, scrollContainer具有overflow-y:scroll規則和一個內部較大的div,名為inner

在內部div中,我有一些文本和輸入。 在輸入上,我應用了一個名為getPosition的屬性指令,該指令應在滾動事件中返回輸入相對於scrollContainer頂部的確切位置。

這就是我需要的: 在此處輸入圖片說明

這是示例角度應用程序: https : //codepen.io/neptune01/pen/vapmLQ

如您所見,嘗試過使用offsetTop和其他dom屬性,但是我找不到任何能滿足我需要的東西。

我建議結合使用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;

您不只是從內部頂部減去外部頂部而忽略滾動位置的原因是因為在進行計算的同時滾動的可能性很小,因為getBoundingClientRect()僅占用了偏移量考慮從視圖邊緣到元素的距離,而scrollY顯示從視圖邊緣到文檔頂部的距離。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM