div로 progress bar 만들기 (scroll indicator)
2022. 8. 2. 18:25ㆍjavaScript
progress태그로 만들어도 되지만 이 경우 진행도에 따라 색이 채워지는? 영역을 색상이나 크기 외에는 조절할 수 없어서 div로 똑같은 기능을 하는 progress bar를 만들 수 있는 방법이 w3c에 올라와있어서 참고했다
HTML
<div class="progress-container>
<div class="progress-bar" id="myBar"></div>
</div>
CSS
맨위, 가로로
.progress-container {
position: fixed;
top: 0;
width: 100%;
height: 8px;
background: #ccc;
}
.progress-bar {
width: 0%;
height: 8px;
background: #04aa6d;
}
맨 왼쪽, 세로로
.progress-container {
position: fixed;
top: 0;
left: 0;
width: 8px;
height: 100%;
background: #ccc;
}
.progress-bar {
width: 8px;
height: 0%;
background: #04aa6d;
}
JS
window.onscroll = function(){myFunction()};
function myFunction(){
let winscroll = document.body.scrollTop || doccument.documentElement.srollTop;
let height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
let scrolled = ((winScroll / height) * 100);
document.getElementById("myBar").style.height = scrolled + "%";
}
위 스크립트는 progress-bar가 0에서 시작하는 기본 양식이다.
만약, 아래 이미지와 같이 처음부터 progress-bar가 채워진 상태처럼 만들려면 다음과 같다
window.onscroll = function(){myFunction()};
function myFunction(){
let winscroll = document.body.scrollTop || doccument.documentElement.srollTop;
let height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
let scrolled = ((winScroll / height) * 100);
document.getElementById("myBar").style.height = 25 + scrolled/1.333 + "%";
}
스크립트 마지막 줄의 값만 변경해주면 된다.
처음 로딩되었을 때 보여지고 싶은 값(25)을 더하면 progress-bar의 총 높이값은 위 스크립트 기준으로 125%가 된다.
총 높이값을 100%로 맞추기 위해서는 scrolled의 값을 나눠서 100의 근사치가 되게끔 하면 된다.
+)progress-bar를 따라오는 텍스트
각 페이지를 설명하는 텍스트를 progress-bar에 맞춰서 변경하고 싶다면 아래와 같다
HTML
<div class="progress-container">
<div class="progress-bar" id="myBar">
<div class="text">영역1</div>
</div>
</div>
progress-bar의 자식요소로 텍스트를 넣어준다
첫 페이지를 설명하는 타이틀 혹은 글씨를 작성해주면 된다
JS
window.onscroll = function(){myFunction()};
function myFunction(){
let winscroll = document.body.scrollTop || doccument.documentElement.srollTop;
let height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
let scrolled = ((winScroll / height) * 100);
document.getElementById("myBar").style.height = 25 + scrolled/1.333 + "%";
const text = document.querySelector(".progress-bar .text");
if(scrolled <= 25){
text.innerText = "영역1"
} else if(Math.floor(scrolled) <= 50){
text.innerText = "영역2"
} else if(Math.floor(scrolled) <= 75){
text.innerText = "영역3"
} else {
text.innerText = "영역4";
}
}
개발자도구로 progress-bar의 높이값을 보면서 각 if문에 원하는 높이값을 넣으면 된다.
참고사이트
https://www.w3schools.com/howto/howto_js_scroll_indicator.asp
'javaScript' 카테고리의 다른 글
tab 클릭 시 css 변경 (0) | 2022.10.24 |
---|---|
JS로 별모양 찍기 (for문) (0) | 2022.08.25 |
scrollTo를 이용한 맨 위로 / 맨 아래로 버튼 만들기 (0) | 2022.07.22 |
버튼 필터링 + 검색어 입력 후 검색버튼 클릭(select option 선택 후 주제에 따라 검색하는 기능) javaScript (0) | 2022.04.25 |
스크롤 이벤트_fade In(페이드인)(vanilla js + css) (0) | 2022.04.04 |