如何计算可滚动<ul>与嵌套<li>元素的顶部像素间距?
<ul> Top and <li> Top Let's break down how to implement the getDistance(ul, li) function to return the pixel distance between the top of your scrollable <ul> and the top of the target <li>.
Understanding the Context
Your <ul> has a fixed maximum height, so it will scroll vertically when its content exceeds that limit. We need to account for both the inherent position of the <li> within the <ul> and any scrolling that’s been applied to the <ul> itself.
Solution 1: Static Distance (Ignoring Scroll)
If you want the fixed distance between the <ul>'s inner top edge (not its visible viewport) and the <li>'s top edge, use the offsetTop property. Since your <li> elements are set to display: block, their offsetParent will be the <ul>—so li.offsetTop directly gives this static distance:
function getDistance(ul, li) { return li.offsetTop; }
Solution 2: Visible Distance (Accounting for Scroll)
If you need the current visible distance between the top of the <ul>'s scrollable viewport and the <li>'s top (i.e., how far the <li> is from the top of what you can see in the <ul>), subtract the <ul>'s scroll offset from the <li>'s offsetTop:
function getDistance(ul, li) { return li.offsetTop - ul.scrollTop; }
Solution 3: Viewport-Relative Distance
If you want the distance between the <ul>'s on-screen top edge and the <li>'s on-screen top edge (relative to the browser viewport), use getBoundingClientRect()—this accounts for both the <ul>'s scroll and the page's overall scroll:
function getDistance(ul, li) { const ulViewportPos = ul.getBoundingClientRect(); const liViewportPos = li.getBoundingClientRect(); return liViewportPos.top - ulViewportPos.top; }
Key Notes
offsetTopmeasures distance relative to the element’soffsetParent(here, the<ul>), excluding any scroll on the parent.scrollToptracks how many pixels the<ul>'s content has been scrolled vertically.getBoundingClientRect()returns positions relative to the browser viewport, so this value will change if the user scrolls the entire page (not just the<ul>).
内容的提问来源于stack exchange,提问作者bashkovpd

