통합검색

Javascript

[Javascript] 메뉴 버튼 클릭 시 특정 위치로 스크롤 이동

  • 2025.09.17 15:53:13
 [!]HTML[/!]
 
<ul id="gnb">
    <li><a href="#brand">브랜드</a></li>
    <li><a href="#differentiation">브랜드차별화</a></li>
</ul>


<div id="brand" class="section">
    <h5>브랜드</h5>
</div>

<div id="differentiation" class="section">
    <h5>브랜드 차별화</h5>
</div>



 [!]Javascript[/!]
const hd_gnb = {
    init() {
        this.action();
    },
    action() {
        const btns = document.querySelectorAll('#gnb > li > a');
        const header = document.getElementById('header');
        // 헤더 높이 캐시 + 리사이즈 대응
        let headerHeight = header ? header.offsetHeight : 0;
        const updateHeaderHeight = () => { headerHeight = header ? header.offsetHeight : 0; };
        window.addEventListener('resize', updateHeaderHeight);
        for (const btn of btns) {
            btn.addEventListener('click', (e) => {
                const href = btn.getAttribute('href');
                if (!href || !href.startsWith('#')) return; // 외부 링크 패스
                e.preventDefault();
                const target = document.querySelector(href);
                if (!target) return;
                // 뷰포트 기준 top + 현재 스크롤 - 헤더높이
                const y = target.getBoundingClientRect().top + window.pageYOffset - headerHeight;
                window.scrollTo({ top: y, behavior: 'smooth' });
            });
        }
    }
};
document.addEventListener('DOMContentLoaded', () => {
    if (document.querySelectorAll('#gnb > li > a').length > 0) {
        hd_gnb.init();
    }
});