javascript - 在页面上的特定点开始滚动指示器
问题描述
我正在使用下面的 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>
推荐阅读
- javafx - 如何在 JavaFX 8 中使用时间微调器?
- jupyterhub - 如何使用帮助程序包?
- javascript - 如何创建订单汇总组件
- mysql - 根据输入(如“otb”到“bot”)创建单词
- mysql - 在交易中更新和选择,无法获取数据
- node.js - Cannot connect to database The `uri` parameter to `openUri()` must be a string, got "undefined"
- jenkins - 由于 OOM-Kill,Jenkins 没有在 redhat linux 中启动
- r - 在管道中使用 bind_rows
- css - 将多个 CSS 动画合并为一个
- elasticsearch - 无法使用 docker logstash 建立索引