#TIL25

전혜린·2021년 8월 23일
0

Today I Learned

목록 보기
40/64

scrollIntoView()

  • scrollIntoView()가 호출 된 요소가 사용자에게 표시되도록 요소의 상위 컨테이너를 스크롤 함
  • behavior 속성: 전환 애니메이션을 정의, "smooth" 값으로 지정시 부드럽게 스크롤됨(기본값: auto)

 
<예시>
 
1.


2.

<script>
function scrollIntoView(selector) {
  const scrollTo = document.querySelector(selector);
  scrollTo.scrollIntoView({behavior: "smooth"});
}
</script>

Element.getBoundingClientRect()

  • 요소의 크기와 뷰포트에 상대적인 위치를 반환
  • top, right, bottom, left는 스크롤 위치가 변경될 때마다 값이 변경됨(해당 값은 절대값이 아니라 뷰포트에 상대적이기 때문)
  • width와 height은 뷰포트의 왼쪽 상단을 기준으로 함
  • width, height 속성의 DOMRect에는 콘텐츠 너비/높이뿐만 아니라 padding 포함

    출처) https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

<예시>
 
1.


2.

// Make home slowly fade to transparent as the window scrolls down

<script>
const home = document.querySelector('.home__container');
const homeHeight = home.getBoundingClientRect().height;
document.addEventListener('scroll', () => {
  home.style.opacity = 1 - window.scrollY / homeHeight;
});
</script>  

 
3.

// Show "arrow up" button when scrolling down
  
<script>
const arrowUp = document.querySelector('.arrow-up');
document.addEventListener('scroll', () => {
  if (window.scrollY > homeHeight / 2) {
    arrowUp.classList.add('visible');
  } else {
    arrowUp.classList.remove('visible');
  }
});
</script>

 
4.

// Make navbar transparent when it is on the top

<script>
const navbar = document.querySelector('#navbar');
const navbarHeight = navbar.getBoundingClientRect().height;
document.addEventListener('scroll', () => {
  if (window.scrollY > navbarHeight) {
    navbar.classList.add('navbar--dark');
  } else {
    navbar.classList.remove('navbar--dark');
  }
});
</script>
profile
코딩쪼아

0개의 댓글