본문 바로가기
Front-end/Javascript 실습

web APIs - 윈도우 스크롤링 APIs

by warrior.p 2022. 3. 13.
<!DOCTYPE html>
<html lang="en">
  <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>Document</title>
    <style>
      body {
        background-color: black;
      }
      div {
        width: 250px;
        height: 250px;
        margin-bottom: 5px;
        background-color: yellow;
        border-radius: 10%;
      }
      .special {
        background-color: salmon;
      }
      .btn {
        position: fixed;
        top: 20px;
        right: 20px;
      }
    </style>
  </head>
  <body>
    <div></div>
    <div></div>
    <div></div>
    <div class="special"></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <aside class="btn">
      <button id="first_btn" , type="button">scroll by</button>
      <button id="second_btn" , type="button">scroll to</button>
      <button id="third_btn" , type="button">scroll into</button>
    </aside>
    <script>
      const special = document.querySelector('.special');
      special.addEventListener('click', event => {
        const rect = special.getBoundingClientRect();
        console.log(rect);
        console.log(`client: ${event.clientX}, ${event.clientY}`);
        console.log(`page: ${event.pageX}, ${event.pageY}`);
      });

      const first = document.querySelector('#first_btn');
      first_btn.addEventListener('click', event => {
        // window.scrollBy(0, 100);
        window.scrollBy({ top: 100, left: 0, behavior: 'smooth' });
      });

      const second = document.querySelector('#second_btn');
      second_btn.addEventListener('click', event => {
        window.scrollTo(0, 100);
      });
      const third = document.querySelector('#third_btn');
      third_btn.addEventListener('click', event => {
        special.scrollIntoView();
      });
    </script>
  </body>
</html>

 

scrollBy ()

scrollTo ()

scrollIntoView ()