menu click 시 스무스하게 스크롤되도록.
CSS 영역
body, html {
scroll-behavior: smooth;
/* 스크롤이 스무스하게 움직이려면 필수!! */
}
header {
position:fixed;
top: 0;
z-index:100;
width: 100%;
}
.gnb {
display: flex;
justify-content: center;
}
.gnb li a {
display:inline-block;
color: #fff;
text-decoration: none;
padding: 20px 30px;
}
JS 영역
window.onload = function(){
let menulist = document.querySelector('.gnb li a');
// section.scroll. menu click 시 스크롤될 section
let contents = document.querySelectorAll('.scroll');
let doc = document.querySelector('html, body');
menulist.addEventListener('click', (e) => {
// index 번호
let idx = this.index();
// 메뉴 스크롤되었을때 section의 번호
let sectionIdx = contents.eq(idx);
// 해당 section의 스크롤 높이
let offSetTop = sectionIdx.offset().top;
doc.stop().animate({scrollTop: offSetTop}, 800);
return false;
});
}
See the Pen menu click scroll by jeunseon (@jeunseon) on CodePen.
'JS' 카테고리의 다른 글
top 버튼 click scroll / javascript (0) | 2024.08.20 |
---|---|
scrolla.js 사용법 (0) | 2024.07.26 |
scrolla.js (0) | 2024.07.25 |