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

如何计算元素在窗口内的滚动位置百分比?

修正元素滚动位置百分比计算逻辑

按照你定义的规则:

  • 0%:元素顶部位于窗口底部(元素尚未显示)
  • 100%:元素底部位于窗口顶部(元素已完全显示)

以下是修正后的实现代码:

JavaScript 代码

function getElemScrollPercent(selector){
  const el = document.querySelector(selector);
  const out = el.querySelector('.out');
  
  function calc(){
    const rect = el.getBoundingClientRect();
    const viewportHeight = window.innerHeight;
    const elementHeight = rect.height;
    
    // 总滚动区间:从0%到100%的总距离(视口高度+元素高度)
    const totalScrollRange = viewportHeight + elementHeight;
    // 当前已滚动的距离:从0%位置(元素顶部在窗口底部)到当前位置的距离
    const scrolledDistance = viewportHeight - rect.top;
    // 计算百分比并限制在0-100之间
    let pct = (scrolledDistance / totalScrollRange) * 100;
    pct = Math.max(0, Math.min(100, pct));
    
    out.innerHTML = `${Math.round(pct)}%`;
  }
  
  window.addEventListener('scroll', calc);
  calc();
}

getElemScrollPercent('#one');
getElemScrollPercent('#two');
getElemScrollPercent('#three');

CSS 代码

* { box-sizing: border-box; }
body { display: flex; flex-direction: column; min-height: 400vh }
section {
  height: 100vh;
  position: relative;
  border: 1px solid black;
}
#one   { background:#d1b4b4; }
#two   { background:#b4d1bc; }
#three { background:#b4b5d1; }
.out {
  position: sticky;
  top: 0;
  display: inline-block;
  padding: .5rem;
  background: #CCC;
}

HTML 代码

<section id="one">   <span class='out'>%</span> </section>
<section id="two">   <span class='out'>%</span> </section>
<section id="three"> <span class='out'>%</span> </section>

关键修改说明

  • 替换原错误计算逻辑,基于元素相对视口的位置和定义的关键节点推导正确公式
  • 添加数值范围限制,确保百分比始终在0%-100%区间内,元素完全在视口外时也能显示正确边界值
  • 移除无用的scale变量,简化代码逻辑

内容的提问来源于stack exchange,提问作者Chris Barr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 12:20:33