CSS&JS/⚡Thinkers

[JS + CSS] transform을 이용한 초간단 상단 progress bar 만들기

arancia_ 2021. 12. 14. 15:13

아 왜 홈페이지 가끔 보다보면 상단 스크롤바 같은 애 있잖아. 그걸 progress bar라고 부름. 이걸 초 간단하게 만들어보겠음

미리보기  : https://ohikmyeong.github.io/progress_bar/

 

Progressive Bar

 

ohikmyeong.github.io

 

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Progressive Bar</title>
<link rel="stylesheet" type="text/css" href="./style.css"/>
<script src="./progressBar.js" defer></script>
</head>
<body>
 
<div id="pgs_bar-wrap">
    <div id="pgs_bar" title="진행률 0%"></div>
</div>
 
<div class="cont" style="--i:1">Lorem</div>
<div class="cont" style="--i:2">Lorem</div>
<div class="cont" style="--i:3">Lorem</div>
<div class="cont" style="--i:4">Lorem</div>
<div class="cont" style="--i:5">Lorem</div>
<div class="cont" style="--i:6">Lorem</div>
<div class="cont" style="--i:7">Lorem</div>
<div class="cont" style="--i:8">Lorem</div>
<div class="cont" style="--i:9">Lorem</div>
 
</body>
</html>
cs

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@charset "utf-8";
*{margin:0;padding:0;box-sizing:border-box;}
 
html,body{
    width:100%;min-height:100vh;
    background:#eee;
    font-size:20px;color:#555;}
 
.cont{
    display:flex;flex-flow:column nowrap;
    justify-content:center; align-items:center;
    width:100%;height:100vh;
    background:rgba( calc(13 * var(--i)),calc(23 * var(--i)),calc(33 * var(--i)));
    font-size:10vw; color:#fff;}
 
/* progressive bar */
#pgs_bar-wrap{
    position:fixed;
    top:0;left:0;
    width:100%;height:6px;
    background:rgba(150,150,150,.5);}
 
#pgs_bar{
    position:absolute;
    top:0;left:0;
    width:100%;height:100%;
    background:rgb(15, 253, 154);
    box-shadow:0 2px 4px rgba(0,0,0,.1);
    transform-origin:left center;
    transform:scaleX(0);}
cs

JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const pgs_bar = document.getElementById('pgs_bar');
let page_hei;
 
function get_page_hei(){
    page_hei = document.body.offsetHeight - window.innerHeight;
}//get_page_hei
 
function progress_bar(){
    const scY = window.scrollY;
    const per = scY / page_hei;
    pgs_bar.style.transform = `scaleX(${per})`;
}//progress_bar
 
/////// 실행 /////////
get_page_hei();
 
window.addEventListener('scroll',progress_bar);
 
window.addEventListener('resize',()=>{
    get_page_hei();
    progress_bar();
});
cs

 

엄청 간단하쥬