scroll
요소가 스크롤될 때 발생합니다.
스크롤값 구하기
let scrollTop = 0;
window.addEventListener('scroll', function () {
scrollTop = document.documentElement.scrollTop;
console.log("스크롤 값: " + scrollTop)
},false)
가로 진행 바 만들기 예제
<h1>스크롤</h1>
<div class="progress">
<span class="bar"></span>
</div>
body {
height: 10000px;
background: linear-gradient(150deg, #937DC2, #C689C6, #E8A0BF, #FCC5C0);
}
.progress {
width: 100%;
position: fixed;
height: 5px;
top: 0;
left: 0;
background-color: black;
z-index: 10;
}
.bar {
width: 100%;
position: absolute;
height: 5px;
top: 0;
left: 0;
background-color: yellow;
z-index: 11;
}
let scrollTop = 0;
let bar;
window.onload = function() {
bar = document.getElementsByClassName("bar")[0];
}
window.addEventListener('scroll', function () {
scrollTop = document.documentElement.scrollTop;
// console.log("스크롤 값: " + scrollTop)
let per = Math.ceil(
scrollTop / (document.body.scrollHeight - window.outerHeight) * 100
);
console.log(per)
bar.style.width = per + "%";
},false)
세로 진행 바로 변경
body {
height: 10000px;
background: linear-gradient(150deg, #937DC2, #C689C6, #E8A0BF, #FCC5C0);
}
.progress {
width: 4px;
position: fixed;
height: 140px;
top: 40%;
left: 10px;
background-color: black;
z-index: 10;
}
.bar {
width: 4px;
position: absolute;
height: 5px;
top: 0;
left: 0;
background-color: yellow;
z-index: 11;
}
let scrollTop = 0;
let bar;
window.onload = function() {
bar = document.getElementsByClassName("bar")[0];
}
window.addEventListener('scroll', function () {
scrollTop = document.documentElement.scrollTop;
// console.log("스크롤 값: " + scrollTop)
let per = Math.ceil(
scrollTop / (document.body.scrollHeight - window.outerHeight) * 100
);
console.log(per)
// bar.style.width를 bar.style.height로 수정
bar.style.height = per + "%";
},false)