인터랙티브 웹 개발(scrollTop)

Dev_Go·2022년 6월 29일
0
post-thumbnail

scroll


scroll요소가 스크롤될 때 발생합니다.

스크롤값 구하기

    let scrollTop = 0;

    window.addEventListener('scroll', function () {
      scrollTop = document.documentElement.scrollTop;
      console.log("스크롤 값: " + scrollTop)
    },false)


scroll 백분율 구하기


가로 진행 바 만들기 예제

예제보기

HTML

  <h1>스크롤</h1>
  <div class="progress">
    <span class="bar"></span>
  </div>

CSS

    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;
    }

JS

    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)

세로 진행 바로 변경

CSS

    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;
    }

JS

    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)

profile
프론트엔드 4년차

0개의 댓글