如何計算元素滾動位置的百分比?
P粉786800174
P粉786800174 2024-04-03 19:55:00
0
1
412

我想以百分比形式計算視窗內元素的滾動位置。

  • 0% 是元素頂部位於視窗底部的位置(尚未顯示)
  • 100% 是元素底部位於視窗頂部的位置(所有元素已顯示)

我很接近,但我知道我在思考數學中的一些錯誤。我製作了一個小演示來顯示多個元素的滾動百分比,但百分比都是錯誤的。

function getElemScrollPercent(selector){
  const scale = 0.1;
  const el = document.querySelector(selector);
  const out = el.querySelector('.out');
  
  function calc(){
    const rect = el.getBoundingClientRect();

    //don't bother calculating if it's off screen
    if (rect.top < window.innerHeight && rect.bottom > 0) {
      const total = (window.scrollY) / (rect.bottom + rect.height);
      const pct = total * 100;

      out.innerHTML = `${Math.round(pct)}%`;
    }
  }
  
  window.addEventListener('scroll', calc);
  calc();
}

getElemScrollPercent('#one');
getElemScrollPercent('#two');
getElemScrollPercent('#three');
* { 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;
}
<section id="one">   <span class='out'>%</span> </section>
<section id="two">   <span class='out'>%</span> </section>
<section id="three"> <span class='out'>%</span> </section>

P粉786800174
P粉786800174

全部回覆(1)
P粉178132828

正如您所指出的,我認為您在這些行中的數學有問題:

const total = (window.scrollY) / (rect.bottom + rect.height);
  const pct = total * 100;

嘗試用以下命令更改這些行:

const scrollableDistance = window.innerHeight + rect.height;
const scrolled = window.innerHeight - rect.top;

const pct = (scrolled / scrollableDistance) * 100;

請告訴我這是否可以解決您的問題,以便我可以提出其他建議。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!