본문 바로가기
JavaScript

[JavaScript] 모달창 빨리 만들기

by teamnova 2021. 5. 5.

이번 예제에서는 스틱코드 플러그인을 이용해서 모달창을 만들어보겠습니다.

 

<이번에 사용하는 코드>

stickode.com/detail.html?no=2090

 

스틱코드

 

stickode.com

 

1. html 작성 (main.html)

스틱코드 단축 자동완성 호출 태그 : modal_html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>stickcode_modal</title>
    <link rel="stylesheet" href="main.css">
</head>
<body>
<button type='button' id="modal_btn">모달창 키기</button>
<div class="modal_background"></div>
<div class="modal_wrap">
    <div class="modal_close"><img class="closeImg" src="closeImg.png" alt="x버튼"></div>
    <div class="text">
        스틱코드에서 개발에 필요한 모든 코드를 쉽게 사용하세요.
        https://stickode.com/mainlogin.html
    </div>
</div>
</body>
<script src="main.js"></script>
</html>

- link태그와 script태그를 이용해서 앞으로 만들 css파일과 js코드를 연결합니다.

- 모달창 키는 버튼, 모달 백그라운드, 모달 닫기 버튼, 모달 안에 들어갈 택스트 등 레이아웃을 짭니다.

 

2. css 작성 (main.css)

스틱코드 단축 자동완성 호출 태그 : modal_css

#modal_btn {
    width: 500px;
    height: 100px;
}

.modal_wrap {
    display: none;
    width: 500px;
    height: 500px;
    position: absolute;
    border: 2px solid black;
    top:50%;
    left: 50%;
    margin: -250px 0 0 -250px;
    background:#eee;
    z-index: 2;
}
.modal_background {
    display: none;
    position: absolute;
    width: 100%;
    height: 100%;
    background-color:rgba(0, 0,0, 0.5);
    top:0;
    left: 0;
    z-index: 1;
}
.modal_close {
    width: 26px;
    height: 26px;
    position: absolute;
    top: 10px;
    right: 10px;
}

.modal_wrap .text {
    margin-top: 45px;
    margin-left: 5px;
}

.modal_close .closeImg {
    display: block;
    width: 100%;
    height: 100%;
}

 

- 앞에서 짜놓은 html에 맞추어 css를 짭니다.

 

3. javascript 작성 (main.js)

스틱코드 단축 자동완성 호출 태그 : modal_js

// 모달 열기
function modalOpen() {
    document.querySelector('.modal_wrap').style.display = 'block';
    document.querySelector('.modal_background').style.display = 'block';
}

// 모달 끄기
function modalClose() {
    document.querySelector('.modal_wrap').style.display = 'none';
    document.querySelector('.modal_background').style.display = 'none';
}


//버튼 클릭리스너 달기
document.querySelector('#modal_btn').addEventListener('click', modalOpen);
document.querySelector('.modal_close').addEventListener('click', modalClose);

html과 css를 사용해서 레이아웃을 만들었다면 이번엔 자바스크립트를 이용해서 모달을 끄고 켜봅시다.

이번 예제예서는 clickListener와 style값을 이용하여 구현하였습니다.

 

※display 속성

  • none : 보이지 않음
  • block : 블록 박스
  • inline : 인라인 박스
  • inline-block : block과 inline의 중간 형태

"모달창 키기" 버튼을 눌렀을 때 display 속성을 block으로 주어 모달과 모달 백그라운드가 보이게 하고

모달의 X 버튼을 눌렀을 때 display 속성을 none으로 주어 모달과 모달 백그라운드가 보이지 않게 코드를 작성합니다.


<결과물>

이렇게 스틱코드를 이용해 모달창을 만들어보았습니다.

다른 포스팅으로 만나요~