Creates a progress bar indicating the scroll percentage of the page.
- Use
position: fixed
and a largez-index
value to place the element at the top of the page and above any content. - Use
EventTarget.addEventListener()
andElement.scrollTop
to determine the scroll percentage of the document and apply it to thewidth
of the element.
预览
HTML
<div id="scroll-progress"></div>
CSS
body {
min-height: 200vh;
}
#scroll-progress {
position: fixed;
top: 0;
width: 0%;
height: 4px;
background: #7983ff;
z-index: 10000;
}
JavaScript
const scrollProgress = document.getElementById('scroll-progress');
const height =
document.documentElement.scrollHeight - document.documentElement.clientHeight;
window.addEventListener('scroll', () => {
const scrollTop =
document.body.scrollTop || document.documentElement.scrollTop;
scrollProgress.style.width = `${(scrollTop / height) * 100}%`;
});
翻译自:https://www.30secondsofcode.org/css/s/scroll-progress-bar