탭클릭시 스크롤앵커

beomhak lee·2023년 8월 23일

work_tip

목록 보기
2/37

작업시 종종 쓰이는 스크롤 앵커 소스입니다.


<div id="wrap">
        <div style="height:600px; background:teal"></div>
        <div class="tabs sticky">
            <a href="#link1" data-scroll="link1" class="tab active">메뉴1</a>
            <a href="#link2" data-scroll="link2" class="tab">메뉴2</a>
            <a href="#link3" data-scroll="link3" class="tab">메뉴3</a>
        </div>
        <div style="height:600px; background:blue"></div>
        <div style="height:600px; background:yellow" ></div>
        <div style="height:600px; background:tomato" class="pannel" id="link1"></div>
        <div style="height:600px; background:purple" class="pannel" id="link2"></div>
        <div style="height:600px; background:yellow" ></div>
        <div style="height:600px; background:blue" class="pannel" id="link3"></div>
        <div style="height:600px; background:tomato" ></div>
    </div>

tab메뉴에 data 이름과 클래스를 지정해줍니다.

#wrap a {color:#ccc; text-decoration: none; display: inline-block;}
#wrap a.active {color:#111; padding-bottom:10px;}
#wrap a.active::before {display: block; width:50px; height:3px; margin-top:10px; content:''; position:absolute; bottom:0; background:#000;}
#wrap .tabs {display: flex; gap:10px; background:#fff;}
#wrap .tabs.sticky {position:sticky; top:0; left:0; z-index: 2;}

tab메뉴에 스티키를 넣어주고 active시 보여지는 스타일을 만들어줍니다.

$(function(){
            var link = $('.tab');
            link.click(function(e){
                var target = $($(this).attr('href'));

                $('html, body').animate({
                    scrollTop: target.offset().top -30
                },600);
                e.preventDefault();
            })
            $(window).scroll(function(){
                findPosition();
            })
            function findPosition(){
                $('.pannel').each(function(){
                    if($(this).offset().top - $(window).scrollTop() < 50){
                        link.removeClass('active');
                        $('.tabs').find(`[data-scroll="${$(this).attr('id')}"]`).addClass('active');
                    }
                })
            }
            findPosition();
        })

href, attr을 이용해 클릭시 이동스크롤을 지정해주고,
스크롤시 특정 함수를 실행시켜주어
영역 패널의 위치값 - 스크롤값이 50보다 작을시
active 클래스를 제거해주고,
data-scroll 의 해당 id 값을 찾아 active 클래스를 붙여줍니다.

0개의 댓글