2016-11-04 75 views
2

Child distance from top parent從父頂部

獲取子元素距離比方說,我有一個內部的div滾動的<li>元素和滾動被設置爲顯示在視窗中該元素。

我需要獲取該元素和其可滾動父級之間的距離,如上圖所示,但element.getBoundingClientRect().topelement.offsetTop都給我提供了錯誤的值。可以這樣做嗎?

我發了筆,把事情稍微容易一些:

http://codepen.io/Darksoulsong/pen/LbYMex

一塊我的代碼:

document.addEventListener("DOMContentLoaded", function(event) { 
    var selectedEl = document.getElementById('consequatur-51'); 
    var selectedElRect = selectedEl.getBoundingClientRect(); 
    var sidebar = document.getElementById('sidebar'); 
    sidebar.scrollTop = selectedEl.offsetTop - 60; 

    document.getElementById('offsetTop').innerText = selectedEl.offsetTop; 
    document.getElementById('rectTop').innerText = selectedElRect.top; 
}); 

回答

0

之間距離我發現瞭如何使其發揮作用。其實,@Dummy的回答給了我一些重要的見解。

基本上,公式是:

childElementDistanceFromParentTop = actualChildElementDistancefromTop - parentElementDistanceFromTop 

有了這些座標我甚至可以告訴我們,如果元素中視或不可見。

更新筆:http://codepen.io/Darksoulsong/pen/rWawrZ

1
var parentTop = parentElem.getBoundingClientRect().top; // Initial parent's top distance from the top of the viewport; 

var currentChildTop = childElement.getBoundingClientRect().top; // Initial child's top distance from the top of the viewport; 

如果你這樣做var childParentDistance = Math.abs(parentTop - currentChildTop),你會得到子元素與其父元素之間的初始距離。但是當你滾動時,你需要考慮滾動量。像這樣

var scrolledParentDistance= Math.abs(parentTop - parentElem.getBoundingClientRect().top); 

,如果你從childParentDistance減去scrolledParentDistance,你會得到這樣的孩子,其父

+1

你'scrolledParentDistance'將始終爲0 – Oriol

+0

號如果你有滾動的元素,當滾動裏面的內容了'top'會發生變化。所以當你滾動'getBoundingClientRect()。top'也會改變。只是你知道'getBoundingClientRect()。top'返回從當前時間點的元素頂部到視口頂部的距離,它不是一個固定值 – Dummy

+0

好吧,你定義了'parentTop = parentElem.getBoundingClientRect ().top',然後是'parentTop - parentElem.getBoundingClientRect().top'基本上是'parentTop - parentTop',所以'0'。 – Oriol