프로그래밍 언어/JAVASCRIPT

[JAVASCRIPT] 윈도우 스크롤 위치

doomole 2020. 12. 11. 15:16
728x90

홈페이지를 만들 때, 길이 아래로 길어지게 된다면 아래 동영상처럼 내비게이션 바를 만들 때가 있다.

클릭을 해서 해당 contents로 이동이 가능해야 하고, 스크롤로 이동할 때도 현재 스크롤 위치에 맞춰서 바의 모양도 변경이 되어야 하는데, 이 때 필요한 것이 window.scroll() 이다.

$(window).scroll(function () { 
    var scrollValue = $(document).scrollTop();

    console.log(scrollValue);

});

 

해당 함수를 소스에 적용하고 웹에서 개발자 도구를 연 후에 스크롤을 이동시켜보면 현재 스크롤의 위치가

console.log를 통해 보이게 된다.

 

<div id="test1">TEST1</div>
<div id="test2">TEST2</div>
<div id="test3">TEST3</div>
<div id="test4">TEST4</div>

<script>
var position_top_test1 = $("#test1").offset().top;
var position_top_test2 = $("#test2").offset().top;
var position_top_test3 = $("#test3").offset().top;
var position_top_test4 = $("#test4").offset().top;
</script>

 

위와 같이 4개의 div가 있을 경우 해당 div의 top 위치를 변수에 담아놓고

scroll의 위치와 비교하여 nav를 이동시키도록 설정할 수 있다.