본문 바로가기

I LOVE WHAT I DO

0과 1 사이, 새로운 시작!

코드 한 줄이 세상을 바꾼다.

부족하지만 최선을 다하면 된다.

무한 스크롤 기능 만들기

by 드비디
JS

수직정렬을 위하여 body 높이를 구할때 유용하게 사용할 수 있다.

body 높이 : document.body.scrollHeight

 

아래 코드로 브라우저의 높이와 폭도 간단하게 구할수 있다.

브라우저의 높이 : document.documentElement.clientHeight

브라우저의 폭 : document.documentElement.clientWidth

무한 스크롤 소스가 document.height == window.height + window.scrolltop 으로 계산되서 스크롤이 끝에 닿으면
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>무한스크롤 예제</title>
  <style>
    html, body{ margin: 0; }
    h1 {position: fixed; top: 0; width: 100%; height: 60px; text-align: center; background: white; margin: 0; line-height: 60px;}
    section .box {height: 500px; background: red;}
    section .box p {margin: 0; color: white; padding: 80px 20px;}
    section .box:nth-child(2n) {background: blue;}
  </style>
</head>
<body>         
  <h1>무한스크롤</h1>
  <section>
    <div class="box">
      <p>
        1번째 블록
      </p>
    </div>
    <div class="box">
      <p>
        2번째 블록
      </p>
    </div>
  </section>
  <script>
    var count = 2;
    window.onscroll = function(e) {
      console.log(window.innerHeight , window.scrollY,document.body.offsetHeight)
      if((window.innerHeight + window.scrollY) >= document.body.offsetHeight) { 
        setTimeout(function(){
          var addContent = document.createElement("div");
          addContent.classList.add("box")
          addContent.innerHTML = `<p>${++count}번째 블록</p>`
          document.querySelector('section').appendChild(addContent);
        }, 1000)  
      }
    }
  </script>
</body>
</html>

 

'JS' 카테고리의 다른 글

반응형 크기에 따라 이미지 height 자동 조절하기  (0) 2023.01.31
클릭 시 글 색 변하게 하기  (0) 2023.01.31
JS addEventListener 정리  (0) 2023.01.31
알림 기능 만들기  (0) 2023.01.19
버튼 클릭 시 이벤트  (0) 2023.01.19