231227 개발일지 TIL - [JS]Modal 열렸을 때 스크롤 방지

The Web On Everything·2023년 12월 27일
0

개발일지

목록 보기
230/269

Modal 열렸을 때 바디 스크롤 방지

웹사이트에서 모달을 사용할 때, 모달이 열려 있는 동안에는 웹 페이지의 스크롤을 막아야 하는 경우가 있는데 스크롤이 움직이지 않도록 설정하면 사용자의 경험이 향상되며, 모달 외부의 웹 페이지를 덜 방해 받을 수 있다.

아래 코드에서는 btn.onclick 이벤트가 발생하면 모달이 열리고, document.body.style.overflow 속성을 hidden으로 설정하여 스크롤을 막는다. span.onclick 이벤트나 window.onclick 이벤트가 발생하면 모달이 닫히며, document.body.style.overflow 속성을 auto로 설정하여 스크롤을 다시 허용해준다. 이렇게 하면 모달이 열릴 때 본문의 스크롤이 비활성화되고, 모달이 닫힐 때 다시 활성화된다.

js

const modal = document.getElementById("myModal");
const btn = document.getElementById("myBtn");
const span = document.getElementsByClassName("close")[0];

btn.onclick = function() {
	modal.style.display = "block";
	document.body.style.overflow = "hidden"; // 스크롤 막기
	document.body.style.position = "fixed"; // 추가된 코드
	setTimeout(function (){
		modal.querySelector('.modal-content').classList.add('show');
	}, 50);
}

span.onclick = function() {
	modal.querySelector('.modal-content').classList.remove('show');
	setTimeout(function(){
		modal.style.display = "none";
		document.body.style.overflow = "auto"; // 스크롤 허용
		document.body.style.position = "static";
	}, 1000);
}

window.onclick = function(event) {
	if (event.target == modal) {
		modal.querySelector('.modal-content').classList.remove('show');
		setTimeout(function(){
			modal.style.display = "none";
			document.body.style.overflow = "auto"; // 스크롤 허용
			document.body.style.position = "static";
		}, 1000);
	}
}

css

	.modal {
		display: none;
		position: fixed;
		z-index: 9999;
		left: 0;
		bottom: 0;
		width: 100%;
		height: 100%;
		overflow: auto;
		background-color: rgba(0,0,0,0.4);
	}

	.modal-content {
		background-color: #fefefe;
		margin: auto;
		padding: 20px;
		border: 1px solid #888;
		border-radius: 20px 20px 0 0;
		width: calc(100% - 40px);
		min-height: 50%;
		overflow-x: hidden;
		position: absolute;
		bottom: 0;
		-webkit-transform: translateY(100%);
		transform: translateY(100%);
		-webkit-transition: -webkit-transform 0.5s ease-out;
		transition: transform 0.5s ease-out;
	}

	.modal-content.show {
		-webkit-transform: translateY(0);
		transform: translateY(0);
	}
	.modal-content .close {
		display: block;
		font-size: 24px;
		text-align: right;
	}

	.modal-content .order-list {
		max-height: 300px;
		overflow-y: scroll;
	}

	.item-image {
		width: 45px;
		height: 45px;
	}

	.item-image > img {
		width: 100%;
	}
profile
오늘은 무슨 오류를 만날까?! 널 만나러 가는 길~ LOL

0개의 댓글