獲取子元素距離比方說,我有一個內部的div滾動的<li>
元素和滾動被設置爲顯示在視窗中該元素。
我需要獲取該元素和其可滾動父級之間的距離,如上圖所示,但element.getBoundingClientRect().top
和element.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;
});
你'scrolledParentDistance'將始終爲0 – Oriol
號如果你有滾動的元素,當滾動裏面的內容了'top'會發生變化。所以當你滾動'getBoundingClientRect()。top'也會改變。只是你知道'getBoundingClientRect()。top'返回從當前時間點的元素頂部到視口頂部的距離,它不是一個固定值 – Dummy
好吧,你定義了'parentTop = parentElem.getBoundingClientRect ().top',然後是'parentTop - parentElem.getBoundingClientRect().top'基本上是'parentTop - parentTop',所以'0'。 – Oriol