You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何计算可滚动<ul>与嵌套<li>元素的顶部像素间距?

Calculate Distance Between Scrollable <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

  • offsetTop measures distance relative to the element’s offsetParent (here, the <ul>), excluding any scroll on the parent.
  • scrollTop tracks 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:49:16