首页 > 解决方案 > 在页面上的特定点开始滚动指示器

问题描述

我正在使用下面的 HTML、CSS 和 JavaScript 来使这个滚动指示器工作。我唯一的问题是我希望当用户在页面下方大约 10% 时开始滚动进度。

知道如何完成这项工作吗?

<div class="line" id="scrollIndicator"></div>

<script>
   const scrollIndicatorElt = document.getElementById('scrollIndicator');
const maxScrollableHeight = document.body.scrollHeight - window.innerHeight;
window.addEventListener('scroll', moveScrollIndicator);
    function moveScrollIndicator() {
  const percentage = ((window.scrollY) / maxScrollableHeight) * 100;
  scrollIndicatorElt.style.width = percentage + '%';
}
  </script>
.line {
      background: #00ba74 ;
      height: 7px;
      border-radius: 0px;
      width: 0%;
      position: fixed;
      top: 0;
    z-index: 1;
    }

标签: javascripthtml

解决方案


我认为这可以通过使用 if 语句来完成。

if (percentage >=10){
    scrollIndicatorElt.style.width = percentage + '%';
} else {
    scrollIndicatorElt.style.width = 0 + '%';
}

如果滚动百分比比页面高度高出 10%,这只会扩展指示器。一开始可能很难看到,但是如果您调整窗口以便只有少量的滚动空间,您应该能够看到它在超过 10 之前不会渲染。

const scrollIndicatorElt = document.getElementById('scrollIndicator');
const scrollIndicatorEltTwo = document.getElementById('scrollIndicator2');
var footerHeight = document.getElementsByClassName('footer')[0].clientHeight

const maxScrollableHeight = (document.body.scrollHeight - footerHeight) - window.innerHeight;

//USE THE BELOW TO SEE DIFFERENCE BETWEEN INCLUDING AND NOT INCLUDING FOOTER HEIGHT
//const maxScrollableHeight = document.body.scrollHeight - window.innerHeight

window.addEventListener('scroll', moveScrollIndicator);

function moveScrollIndicator() {
  const percentage = ((window.scrollY) / maxScrollableHeight) * 100;
  if (percentage >= 10) {
    scrollIndicatorElt.style.width = (percentage - 10) + '%';
    scrollIndicatorEltTwo.style.width = percentage + '%';
  } else {
    scrollIndicatorElt.style.width = 0 + '%';
    scrollIndicatorEltTwo.style.width = 0 + '%';
  }
}
#scrollIndicator {
  height: 20px;
  border: solid 1px black;
  position: fixed;
}

#scrollIndicator2 {
  height: 20px;
  border: solid 1px black;
  position: fixed;
  top: 35px;
}

.footer {
  position: absolute;
  bottom: 0px;
  width: 100%;
  border: solid 1px black;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}
<div style='height: 1000px; position: relative;'>
  <div class="line" id="scrollIndicator">
  </div>
  <div class="line" id="scrollIndicator2">
  </div>
  <div class="footer">
    HERE IS YOUR FOOTER
  </div>
</div>


推荐阅读