gpt4 book ai didi

javascript - 在页面上的特定点开始滚动指示器

转载 作者:行者123 更新时间:2023-11-30 19:06:13 26 4
gpt4 key购买 nike

我使用下面的 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>

关于javascript - 在页面上的特定点开始滚动指示器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58963882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com