공부기록/바닐라 자바스크립트

자바스크립트 특정 위치로 이동하기

_우지 2022. 6. 16. 15:35

 

유튜브 자료를 보고 공부한 내용입니다.

 

window.scroll() 

브라우저의 스크롤을 특정 위치로 이동시킬 수 있는 메소드이다.

 

1. window.scroll(x좌표,y좌표)

2. window.scroll(options 객체)

 

offsetTop

요소의 윗면 경계가 최상위 요소의 윗면 경계와 (쉽게 말해 브라우저 화면 맨 위) 얼마 만큼 떨어져 있는지 그 거리를 반환해주는 속성이다.

 

https://www.youtube.com/watch?v=r3G0U5fva1c

 

html

<!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>
    <link rel="stylesheet" href="./css/scroll.css" />
  </head>
  <body>
    <div class="menu">
      <span>1번</span>
      <span>2번</span>
      <span>3번</span>
    </div>
    <div class="content">1</div>
    <div class="content">2</div>
    <div class="content">3</div>
    <script src="js/ClickToMove.js"></script>
  </body>
</html>

 

css

* {
  box-sizing: border-box;
}
body {
  margin: 0;
}
.menu {
  width: 200px;
  height: 50px;
  position: fixed;
  left: 50px;
  border-radius: 0 0 30px 30px;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: space-around;
  align-items: center;
  color: white;
}

.menu > span:hover {
  border-bottom: 3px solid white;
  cursor: pointer;
}

.content {
  height: 500px;
  display: flex;
  justify-content: center;
  align-items: center;
}

div:nth-child(2) {
  background-color: coral;
}
div:nth-child(3) {
  background-color: violet;
}
div:nth-child(4) {
  background-color: teal;
}

js

const spans = document.querySelectorAll("span");
const contents = document.querySelectorAll(".content");
const firstTop = contents[0].offsetTop;
const secondTop = contents[1].offsetTop;
const thirdTop = contents[2].offsetTop;

spans[0].onclick = function () {
  window.scroll({top: firstTop, behavior: "smooth"});
};

spans[1].onclick = function () {
  window.scroll({top: secondTop, behavior: "smooth"});
};

spans[2].onclick = function () {
  window.scroll({top: thirdTop, behavior: "smooth"});
};