在页面上的特定点启动滚动指示器



我正在使用下面的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;
}

我认为这可以通过使用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>

最新更新