클릭 -> 스크롤 이동을 구현해보도록 하겠다.

scrollintoview()를 사용하면 간단하다.

 

 

HTML

<p>
  클릭하세요
  <button id="box1" type="button">box1</button>
  <button id="box2" type="button">box2</button>
  <button id="box3" type="button">box3</button>
  <button id="box4" type="button">box4</button>
  <button id="box5" type="button">box5</button>
  <button id="box6" type="button">box6</button>
  <button id="box7" type="button">box7</button>
</p>
<div class="box1">박스1입니다.</div>
<div class="box2">박스2입니다.</div>
<div class="box3">박스3입니다.</div>
<div class="box4">박스4입니다.</div>
<div class="box5">박스5입니다.</div>
<div class="box6">박스6입니다.</div>
<div class="box7">박스7입니다.</div>

클릭하여 이동할 수 있게 버튼을 만들어준다.

 

 

CSS

body,div{
  margin:0;
  padding:0;
}

div{
  display: flex;
  align-items: center;
  justify-content: center;
}

.box1{ background-color:red; }
.box2{ background-color:orange; }
.box3{ background-color:yellow; }
.box4{ background-color:green; }
.box5{ background-color:blue; }
.box6{ background-color:navy; }
.box7{ background-color:purple; }

 

 

JS

const btnArr = document.getElementsByTagName('button');

for(let i = 0; i < btnArr.length; i++){

  btnArr[i].addEventListener('click',function(e){
    e.preventDefault();
    document.querySelector('.box' + (i + 1)).scrollIntoView(true);
  });

}

 

버튼의 index를 이용해서 class를 검색하여 엘리먼트를 찾는다.

*index로 찾은 엘리먼트를 통해 scrollIntoView() 해주기 때문에 class나 id가 수정되면 스크립트 오류가난다.

 

예제

예제 버튼 클릭 시 티스토리 스크롤도 top되는 현상이 생겨버렸다.!! codePen가서 해보시길..

See the Pen scrollIntoView example by leeyoonseo (@okayoon) on CodePen.

 

크롬만 테스트했고, scrollintoview 메서드가 궁금하면 MDN을 살펴보자.

https://developer.mozilla.org/ko/docs/Web/API/Element/scrollIntoView

 

 

+ Recent posts