https://ko.javascript.info/size-and-scroll

https://css-tricks.com/debouncing-throttling-explained-examples/
![]()
![]()

스크롤을 올리고 내림에 따라 따라오는 프로그래스 바를 만들어 주기 위해서
먼저
[CSS]
.header {
position: fixed;
top: 0;
z-index: 1;
width: 100%;
background-color: #f1f1f1;
}
.progress-container {
width: 100%;
height: 8px;
background: #c6c6c6;
}
.progress-bar {
height: 8px;
background: #ff9800;
width: 0%;
}
스타일링을 한 후 진행할
progress-bar에 JS 를 넣어준다.
;(function () {
'use strict'
let timerId
const get = (target) => {
return document.querySelector(target)
}
const $progressBar = get('.progress-bar')
const onScroll = () => {
const scrollTop = document.documentElement.scrollTop;
console.log(scrollTop);
const height = //보여지는 영역을 제외한 길이
document.documentElement.scrollHeight - //스크롤의 총길이
document.documentElement.clientHeight //보여지는 영역
//결국 이걸 통해 progress-bar 의 width 값을 채워줄 것임
const scrollWidth = (scrollTop / height) * 100;
$progressBar.style.width = scrollWidth + '%' //스타일 변경
}
window.addEventListener('scroll', () => onScroll())
})()
위 scrollWidth 를 console에서 보면

이렇게 width 값들이 나옴 이걸 통해 프로그래스바 스타일에서 위드값 변경을 해주는 것 (100을 곱한것도 그 이유)
let timerId;
const throttle = (callback, time) => {
if (timerId) return
timerId = setTimeout(() => {
callback()
timerId = undefined; // 한번 실행후 초기화 되게
}, time)
}
;(function () {
'use strict'
let timerId; //throttle 에 쓸 timerID라는 변수 생성
const get = (target) => {
return document.querySelector(target)
}
const $progressBar = get('.progress-bar')
//성능향상에는 좋지만 시각적으로 뚝뚝 끊어져보일 수 있음 - 시간설정 잘 해주면 됨 !
const throttle = (callback, time) => {
if (timerId) return
timerId = setTimeout(() => {
callback()
timerId = undefined; // 한번 실행후 초기화 되게
}, time)
}
const onScroll = () => {
const scrollTop = document.documentElement.scrollTop;
console.log(scrollTop);
const height = //보여지는 영역을 제외한 길이
document.documentElement.scrollHeight - //스크롤의 총길이
document.documentElement.clientHeight //보여지는 영역
const scrollWidth = (scrollTop / height) * 100;
$progressBar.style.width = scrollWidth + '%' //스타일 변경
}
window.addEventListener('scroll', () => {
throttle(onScroll, 100) //throttle (스크롤,원하는시간)
})
})()
죄송합니다... 혹시... html 코드도 부탁드려도 되나요?...