Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

CSS와 JavaScript로 스크롤 진행 표시기 만드는 방법

CSS와 JavaScript를 활용하면 페이지를 아래로 스크롤할수록 점점 채워지는 스크롤 진행 표시기(Scroll Indicator)를 손쉽게 구현할 수 있습니다. 이 기능은 독자가 현재 문서에서 어느 정도까지 읽었는지 시각적으로 보여주기 때문에 블로그나 긴 게시물에서 유용하게 활용됩니다.

동작 원리

스크롤 진행 표시기는 크게 세 가지 요소로 구성됩니다.

  • HTML 구조: 화면 상단에 고정된 헤더 안에 진행 막대를 담을 컨테이너(progressContainer)와 실제로 채워지는 막대(progressBar)를 배치합니다.
  • CSS 스타일링: 헤더를 position: fixed로 고정하고, progressBar의 초기 너비를 0%로 설정해 스크롤에 따라 늘어나도록 준비합니다.
  • JavaScript 로직: window.onscroll 이벤트 발생 시 현재 스크롤 위치를 전체 스크롤 가능 높이로 나눠 백분율을 계산한 후, 그 값을 progressBar의 width에 적용합니다.

전체 예제 코드

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
    body {
        font-size: 28px;
        margin: 0px;
        padding: 0px;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    .header {
        position: fixed;
        top: 0;
        margin-bottom: 100px;
        z-index: 1;
        width: 100%;
        background-color: #ebfffd;
    }
    .progressContainer {
        width: 100%;
        height: 20px;
        background: #ccc;
    }
    .progressBar {
        height: 20px;
        background: #724caf;
        width: 0%;
    }
    .content {
        padding: 100px 0;
        margin: 50px auto 0 auto;
        width: 80%;
    }
</style>
</head>
<body>
<div class="header">
<h1>Scroll indicator example</h1>
<div class="progressContainer">
<div class="progressBar"></div>
</div>
</div>
<div class="content">
<h1>Some headers</h1>
<h1>Some headers</h1>
<h1>Some headers</h1>
<h1>Some headers</h1>
<h1>Some headers</h1>
</div>
<script>
    window.onscroll = function() {showProgress()};
    function showProgress() {
        var scrollCalculate = document.body.scrollTop || document.documentElement.scrollTop;
        var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
        var scrolled = (scrollCalculate / height) * 100;
        document.querySelector(".progressBar").style.width = scrolled + "%";
    }
</script>
</body>
</html>

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

CSS와 JavaScript로 스크롤 진행 표시기 만드는 방법

아래로 스크롤하면 진행 막대가 다음과 같이 점점 채워지는 것을 확인할 수 있습니다.

CSS와 JavaScript로 스크롤 진행 표시기 만드는 방법

정리

핵심은 documentElement.scrollHeight에서 clientHeight(화면에 보이는 영역 높이)를 빼서 실제 남은 스크롤 거리를 구하는 것입니다. 여기에 현재 스크롤 위치(scrollTop)를 나누고 100을 곱하면 진행률(%)이 나오며, 이 값을 막대의 너비에 대입하기만 하면 됩니다. 필요에 따라 막대 색상, 높이, 위치 등은 CSS에서 자유롭게 조절할 수 있습니다.