Position Sticky를 구현하는 Fixed JS 코드 활용

IT/코딩 Javascript

무찌마 / 2021. 10. 5. / 댓글

position sticky effect 코드

1. 원글: Position Sticky를 구현하는 Fixed JS 코드 오류 수정
2. 수정: Position Sticky를 구현하는 Fixed JS 코드 2차 수정본
3. 수정: Position Sticky를 구현하는 Fixed JS 코드 3차 수정본
4. 수정: Position Sticky를 구현하는 Fixed JS 코드 4차 수정본
5. 활용: 본문
cloneNode()를 사용하여 DOM 객체의 복제본을 만들지 않고, siblings()를 사용하여 'position: fixed' 지정할 객체의 위 혹은 아래 객체(element)에 margin 속성을 부여하는 방법입니다.

 

1. 'position: fixed' 객체의 빠져나간 공간을 상위 sibling 객체에 marginBottom을 지정하여 메우는 방법입니다.

- 상위 sibling 객체: upperElement, previousElementSibling

- marginBottom 지정

 

const nav = document.getElementById('header'),
	rectTop = nav.offsetTop,
	rectHeight = nav.offsetHeight,
	upperElement = nav.previousElementSibling;
window.addEventListener('scroll', function() {
	if (window.pageYOffset >= rectTop) {
		nav.className = "fixed";
		upperElement.style.marginBottom = rectHeight + "px";
	} else if (window.pageYOffset < rectTop) {
		nav.className = "";
		upperElement.style.marginBottom = "";
	}
});

JS_How to Position Sticky Effect_BookClub_Skin_NoClone.txt
0.00MB

 

2. 'position: fixed' 객체의 빠져나간 공간을 하위 sibling 객체에 marginTop을 지정하여 메우는 방법입니다.

- 하위 sibling 객체: lowerElement, nextElementSibling

- marginTop 지정

 

const nav = document.getElementById('header'),
	rectTop = nav.offsetTop,
	rectHeight = nav.offsetHeight,
	lowerElement = nav.nextElementSibling;
window.addEventListener('scroll', function() {
	if (window.pageYOffset >= rectTop) {
		nav.className = "fixed";
		lowerElement.style.marginTop = rectHeight + "px";
	} else if (window.pageYOffset < rectTop) {
		nav.className = "";
		lowerElement.style.marginTop = "";
	}
});

 

자신의 HTML 구조에 맞게 1 혹은 2를 선택하고, CSS 파일에 "#header.fixed" 추가해야 합니다.

#header.fixed {
	position: fixed;
	top: 0;
	left: 0;
	}

 

나머지 설명은 페이지 서두의 1, 2, 3, 4 링크로 대신합니다.

그래도 잘 모르는 부분이 있으면 댓글 달아 주세요.


Element.getBoundingClientRect()


The Element.getBoundingClientRect() method returns a DOMRect object providing information about the size of an element and its position relative to the viewport.

Syntax
domRect = element.getBoundingClientRect();

 

Element.getBoundingClientRect() - Web APIs | MDN (mozilla.org)


 

댓글