WebPublisher/JavaScript & jQuery

[jQuery] 따라다니는 내비게이션 sticky navigation menu

amanda 2024. 11. 14. 17:33

HTML

<!-- navigation -->
<div class="navi_wrap js_navi_wrap">
    <ul class="navi_menu js_navi_menu">
        <li>
            <a href="#n" data-target="sec_01" title="section1">
                go to section 1
            </a>
        </li>
        <li>
            <a href="#n" data-target="sec_02" title="section2">
                go to section 2
            </a>
        </li>
    </ul>
</div>

<!-- section 1 -->
<div id="sec_01">
</div>

<!-- section 2 -->
<div id="sec_02">
</div>

 

CSS

/* navigation */
.navi_wrap{
	position: relative;
	z-index: 10;
	height: 97px;
}
.navi_wrap.fixed .navi_menu{
	position: fixed;
	top: 0;
	left: 50%;
	-webkit-transform: translateX(-50%);
	transform: translateX(-50%);
	width: 1200px;
}
.navi_menu{
	display: flex;
}
.navi_menu li{
	width: calc((100% - 51px)/4);
	border: 2px solid transparent;
	border-radius: 0 0 20px 20px;
	text-align: center;
	-webkit-transition: transform 0.3s;
	transition: transform 0.3s;
}
.navi_menu li + li{
	margin-left: 17px;
}
.navi_menu li a{
	display: block;
	padding: 28px 0;
	color: #fff;
	text-align: center;
}
.navi_menu li a span{
	display: inline-block;
	margin-right: 10px;
	font-size: 28px;
	color: #fff;
	vertical-align: middle;
}

 

jQuery

// section scroll event
function tabScroll(){
	$('.js_navi_menu li a').on('click', function(){
		let targetId = $(this).data('target'),
			targetSec = $('#' + targetId).offset().top,
			targetSec1 = targetSec - 200;
		$('html').animate({
			scrollTop : targetSec1
		}, '2000');
		return false;
	})

	//sticky menu
	$(window).scroll(function(){
		let tabMenu = $('.js_navi_wrap'),
			menuTop = tabMenu.offset().top,
			crtTop = $(window).scrollTop();
		if(menuTop < crtTop){
			tabMenu.addClass('fixed');
		}else{
			tabMenu.removeClass('fixed');
		}
	});
}