본문 바로가기
Jquery, Javascript

[Jquery] 스크롤 내렸을때 상단 메뉴 변경

by 준오네 2022. 8. 11.
반응형

스크롤 내렸을때 상단 컨텐츠가 바뀌는 스크립트를 소개합니다.

 

#wrap{width:100%; height:1000px;}
.main{width:100%; height:50px; background-color:blue; text-align:center; line-height:50px;}
.scroll{width:100%; height:50px; position:absolute; left:0; top:0; background-color:green; text-align:center; line-height:50px; color:#fff; font-weight:600;}
<div id="wrap">
  <div class="main">
    상단 메뉴
  </div>
  <div class="scroll">
    스크롤 했을때 상단 메뉴
  </div>
</div>

HTML, 스타일은 위와 같이 설정 해 주었습니다.

 

$(document).ready(function(){

    var mainH = $(".main").height(); 
    //상단 메뉴의 높이 mainH 변수선언

    $(".scroll").hide();
    //스크롤 메뉴 hide

    $(window).scroll(function(){  
        var roll = $(this).scrollTop() >= mainH; 
	// 스크롤의 정도가 mainH 의 값을 넘었을 때 == 윈도우 스크롤의 값이 mainH 의 높이와 같거나 크다

	/*
	scrollTop()은 윈도우에서 가장 높은 위치
	*/

    if(roll){ 
		//윈도우 스크롤 기능의 값이 mainH 의 높이와 같거나 크면
            $(".scroll").show().css({"position":"fixed"});
        }
        else{
            $(".scroll").hide();
        }
    });
    
});

스크롤했을때 hide해주었던 메뉴박스가 fixed되어서 나타나게 됩니다.

반응형

댓글