스크롤 내리면 부드럽게 헤더 줄여주기 | reduce height when onscroll

jango HTML 템플릿에서 사용한 기법을 기준으로 설명해보겠습니다.

 

[components.css]

헤더는 아래와 같이 위/아래 마진을 가지고 있습니다. 헤더는 고유의 배경색상을 가지므로 마진 사이즈에 따라 헤더의 크기가 설정되는 방식이죠.

.c-layout-header .c-brand {margin: 25px 0 30px 0; }

 

그리고 아래와 같이 추가된 셀렉터집합에 마진이 0.2초의 시간에 줄어들도록 애니메이션 처리까지 해주었네요.
.c-page-on-scroll.c-layout-header-fixed .c-layout-header .c-brand {transition: margin 0.2s; margin: 8px 0 9px 0; }

 

* 이번 글의 예시만을 위해서라면 .c-layout-header-fixed 는 필요없습니다.

그러면 ‘언제 어디에 c-page-on-scroll 클래스가 추가되는가?’ 라는 궁금증이 생길텐데요..

 

 

[components.js]

파일에 해답이 있습니다. 헤더의 높이 정도 스크롤이 되면 body 엘러먼트에 c-page-on-scroll 클래스가 추가됩니다.  이번예제와 상관없는 아랫쪽의_handleTopbarCollapse 부분은 빼고 보시면 됩니다.

 

// BEGIN: Layout Header
var LayoutHeader = function () {
var offset = parseInt($(‘.c-layout-header’).attr(‘data-minimize-offset’) > 0 ? parseInt($(‘.c-layout-header’).attr(‘data-minimize-offset’)) : 0);
var _handleHeaderOnScroll = function () {
if ($(window).scrollTop() > offset) {
$(“body”).addClass(“c-page-on-scroll”);
} else {
$(“body”).removeClass(“c-page-on-scroll”);
}
}

var _handleTopbarCollapse = function () {
$(‘.c-layout-header .c-topbar-toggler’).on(‘click’, function (e) {
$(‘.c-layout-header-topbar-collapse’).toggleClass(“c-topbar-expanded”);
});
}

return {
//main function to initiate the module
init: function () {
if ($(‘body’).hasClass(‘c-layout-header-fixed-non-minimized’)) {
return;
}

_handleHeaderOnScroll();
_handleTopbarCollapse();

$(window).scroll(function () {
_handleHeaderOnScroll();
});
}
};
}();
// END