자기소개 페이지를 제작하던 중 마우스 스크롤에 따른 페이지 이동이 되도록 구현하였다.
index.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>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<section style="background-color: aqua; height: 100vh">1</section>
<section style="background-color: aquamarine; height: 100vh">2</section>
<section style="background-color: bisque; height: 100vh">3</section>
<section style="background-color: burlywood; height: 100vh">4</section>
<section style="background-color: coral; height: 100vh">5</section>
</body>
</html>
먼저 5개의 페이지를 section 태그로 생성한다. (section이 아니어도 상관없음)
/* scroll마다 한 페이지씩 이동하기 */
window.onload = function () {
const elm = document.querySelectorAll("section");
const elmCount = elm.length;
elm.forEach(function (item, index) {
item.addEventListener("mousewheel", function (event) {
event.preventDefault();
let delta = 0;
if (!event) event = window.event;
if (event.wheelDelta) {
delta = event.wheelDelta / 120;
if (window.opera) delta = -delta;
} else if (event.detail) delta = -event.detail / 3;
let moveTop = window.scrollY;
let elmSelector = elm[index];
// wheel down : move to next section
if (delta < 0) {
if (elmSelector !== elmCount - 1) {
try {
moveTop =
window.pageYOffset +
elmSelector.nextElementSibling.getBoundingClientRect().top;
} catch (e) {}
}
}
// wheel up : move to previous section
else {
if (elmSelector !== 0 && elmSelector.id !== "home") {
try {
moveTop =
window.pageYOffset +
elmSelector.previousElementSibling.getBoundingClientRect().top;
} catch (e) {}
}
}
const body = document.querySelector("html");
window.scrollTo({ top: moveTop, left: 0, behavior: "smooth" });
});
});
};
그 다음 자바스크립트를 작성해주면 끝
똑같이 했는데 스무스하게 안되는건 어떻게 해야하나요?