Heim  >  Fragen und Antworten  >  Hauptteil

Wie berechnet man den Prozentsatz der Bildlaufposition eines Elements?

Ich möchte die Scrollposition eines Elements innerhalb eines Fensters als Prozentsatz berechnen.

Ich bin nah dran, aber ich weiß, dass ich in der Mathematik etwas Falsches denke. Ich habe eine kleine Demo erstellt, um den Scroll-Prozentsatz für mehrere Elemente anzuzeigen, aber die Prozentsätze sind alle falsch.

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粉786800174P粉786800174180 Tage vor419

Antworte allen(1)Ich werde antworten

  • P粉178132828

    P粉1781328282024-04-04 16:34:28

    正如您所指出的,我认为您在这些行中的数学有问题:

    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;

    请告诉我这是否可以解决您的问题,以便我可以提出其他建议。

    Antwort
    0
  • StornierenAntwort