滚动指示器JavaScript [英] Scroll indicator JavaScript
本文介绍了滚动指示器JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将以下代码用于滚动指示器,该指示器包含在多个页面中.
I use the following code for a scroll indicator which I include on multiple pages.
window.onscroll = function() {
myFunction()
};
function myFunction() {
var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
var scrolled = (winScroll / height) * 100;
document.getElementById("myBar").style.width = scrolled + "%";
}
.progress-container {
width: 100%;
height: 8px;
background: #ccc;
position: fixed;
top: 0;
z-index: 1000;
}
.progress-bar {
height: 8px;
background: #4caf50;
width: 0%;
}
<div class="fixedBar">
<div class="header">
<div class="progress-container">
<div class="progress-bar" id="myBar"></div>
</div>
</div>
</div>
但是由于缺少内容,某些页面无法滚动,我试图使滚动指示器也被填充我无法弄清楚为什么如果无法滚动则无法填充(我不满意JavaScript要么:3)
But some of the pages are not able to scroll due to lack of content I am trying to get the scroll indicator to also be filled I can't figure out why it's not filling if it cant scroll ( I am not good with JavaScript either :3 )
推荐答案
两件事:
- 页面加载后至少执行一次功能
- 检查文档是否没有滚动并在这种情况下设置完整宽度.
这里是:
// When the user scrolls the page, execute myFunction
window.onscroll = function () {
myFunction()
};
// Execute myFunction once when the page is loaded
window.onload = function() {
myFunction();
}
function myFunction() {
var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
var scrolled = 100; // Default value: fill width
// Only if document is scrollable
if (height > 0) {
scrolled = (winScroll / height) * 100;
}
document.getElementById("myBar").style.width = scrolled + "%";
}
这篇关于滚动指示器JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文