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

버튼으로 지정된 곳으로 이동하기

by warrior.p 2022. 3. 17.
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Finding Rabbit</title>
    <style>
      body {
        background-color: black;
        text-align: center;
      }
      img {
        /* 한줄에 하나만 나오게  */
        display: block;
        /* 중앙 정렬 */
        margin: auto;
      }
      button {
        outline: none;
        background-color: red;
        color: white;
        font-size: 32px;
        margin: 16px 0;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <button>Find a rabbit</button>
    <img src="img/carrot.png" alt="carrot" />
    <img src="img/carrot.png" alt="carrot" />
    <img src="img/carrot.png" alt="carrot" />
    <img src="img/carrot.png" alt="carrot" />
    <img src="img/carrot.png" alt="carrot" />
    <img id="rabbit" src="img/rabbit.png" alt="rabbit" />
    <img src="img/carrot.png" alt="carrot" />
    <img src="img/carrot.png" alt="carrot" />
    <img src="img/carrot.png" alt="carrot" />

    <script>
      const button = document.querySelector('button');
      const rabbit = document.querySelector('#rabbit');
      button.addEventListener('click', event => {
        rabbit.scrollIntoView({ behavior: 'smooth', block: 'center' });
         /* behavior: 스크롤 무빙?움직임설정, block : target이 화면 어디에 위치하게할지 선택  */
        
      });
    </script>
  </body>
</html>

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

 

 

Element.scrollIntoView() - Web APIs | MDN

The Element interface's scrollIntoView() method scrolls the element's parent container such that the element on which scrollIntoView() is called is visible to the user.

developer.mozilla.org