vanila Javascript

[javascript] 스크롤에 따라 나타나고 사라지는 헤더 (모바일웹/웹뷰)

julia_ 2021. 9. 24. 17:44

[HTML]

<body>
  <header class="fade">
      header
  </header>
  <section>
    <article class="article1">section1</article>
    <article class="article2">section2</article>
    <article class="article3">section3</article>
    <article class="article4">section4</article>
  </section>   
</body>

[CSS]

* {margin:0; padding: 0;}
body {
  width: 360px;
}
header {
  position: absolute;
  left: 0;
  top: 0;
  width: 360px;
  height: 100px;
  font-weight: 800;
  line-height: 100px;
  text-align: center;
  background-color: #fff;
  opacity:0;
}
header.fade.fixed {
  position: fixed;
  opacity:1;
  z-index: 100;
  border: 1px solid #333;

  -webkit-transition: all 0.8s ease;
  -moz-transition: all 0.8s ease;
  -o-transition: all 0.8s ease;
  transition: all 0.8s ease;
	}
article {
  width: 100%;
  height: 300px;
  line-height: 300px;
  text-align: center;
}
.article1 {
  background-color: orange;
}
.article2 {
  background-color: purple;
}
.article3 {
  background-color: #f3f3f3;
}
.article4 {
  background-color: green;
}

 

 

1. 상단에서 하단으로 스크롤 할때만 나오는 헤더

 

적용 후 모바일에서 테스트 해 보았을때

최하단에서 스크롤링을 할 경우, 헤더가 나타났다 사라지는 현상이 있어

페이지의 총 높이값(sectionHeight)과 페이지의 최하단 스크롤 값(scrollBottom)을 구하여 계산식에 추가해주었다.

 

[JS]

const pageHeader = document.querySelector('header.fade');
const navbarHeight = pageHeader.clientHeight;

let lastScrollTop = 0;

window.addEventListener('scroll', toggleClassFixed);

function toggleClassFixed()
{
  const scrollTop = window.scrollY;
  const section = document.getElementById('section');
  const sectionHeight = section.clientHeight;
  const windowHeight = window.innerHeight;
  const scrollBottom = scrollTop + windowHeight;

if (scrollTop > lastScrollTop && scrollTop > navbarHeight)
  {
  pageHeader.classList.add('fixed');
  }
else 
  {
  pageHeader.classList.remove('fixed');
  }

if ( scrollBottom < sectionHeight) { lastScrollTop = scrollTop; }
}

 

See the Pen by noocgs (@noocgs) on CodePen.

 

 

2.  하단에서 상단으로 스크롤 할때만 나오는 헤더

 

 

[JS]

let lastScrollTop = 0;


window.addEventListener('scroll', toggleFixedHeader);

function toggleFixedHeader()
{
  const scrollTop = window.pageYOffset;

  (scrollTop < 1 || scrollTop > lastScrollTop) ? removeClassFixed() : addClassFixed();

  lastScrollTop = scrollTop;
}

function addClassFixed()
{
  document.querySelector('header.fade').classList.add('fixed');
}

function removeClassFixed()
{
  document.querySelector('header.fade').classList.remove('fixed');
}

See the Pen by noocgs (@noocgs) on CodePen.

 

 

 

[적용화면]