본문 바로가기
프로그래밍 개발/JS 웹

Javascript - 모달창 만들기 기본

by Jinseok Kim 2020. 12. 1.
반응형

 

 

 

간단한 자바스크립 코드를 이용하여 열기 버튼을 클릭하면 모달창이 등장하고 닫기 버튼을 누르면 다시 모달창이 꺼지는 페이지를 구성해보았다.

 

 

 

 

 

CSS

<style>

        
body{
 background:#aa2141
     
        } 
        
#root button{position: absolute; top:50%; left:50%; transform: translate(-50%, -50%);
    background: #bf18b2;
    font-weight: bold;
    display:inline-block;
    font-weight: 100%;
    
        }        
        
#modal {
  display: none;    
  position:relative;
  width:100%;
  height:100%;
  z-index:1;
}

#modal h2 {
  margin:0;
    
}

#modal button {
  display:inline-block;
  width:100px;
    background: #bf18b2;
    font-weight: bold;
  margin-left:calc(100% - 100px - 10px);
}

#modal .modal_content {
  width:300px;
  margin:100px auto;
  padding:20px 10px;
  background:#e326e3;
  border:2px solid #666;
}

#modal .modal_layer {
  position:fixed;
  top:0;
  left:0;
  width:100%;
  height:100%;
  background:rgba(0, 0, 0, 0.5);
  z-index:-1;
}   
</style>
  • 여기서 중요한 부분은 #modal 부분에 display:none;을 해주어  홈페이지를 열었을때 미리 모달창이 뜨지 않게 일단은 설정하였다.
  • 열기 버튼을 눌렀을 때 모달창이 등장하게 자바스크립트 부분에서 제어할 수 있을 것이다.

 

 

 

 

 

 

 

 

Html

<body>

<div id="root">
   
    <button type="button" id="modal_opne_btn">열기</button>
       
</div>

<div id="modal">
   
    <div class="modal_content">
        <h2>확인</h2>
       
        <p>실행 완료되었습니다!</p>
       
        <button type="button" id="modal_close_btn">닫기</button>
       
    </div>
   
    <div class="modal_layer"></div>
</div>

</body>
   

 

 

 

 

 

 

 

 

JS

 <script>
    document.getElementById("modal_opne_btn").onclick = function() {
        document.getElementById("modal").style.display="block";
    }
   
    document.getElementById("modal_close_btn").onclick = function() {
        document.getElementById("modal").style.display="none";
    }   
</script>
  • getElementById 메소드를 사용하여 id 값이 modal_opne_btn인 열기 버튼 요소를 가져와 .onclick 이벤트를 사용하여 클릭하였을 때 function() 함수가 발동되도록 하였다. 닫기 버튼 또한 마찬가지이다.
  • 버튼을 클릭 한 후 getElementById 메소드을 이용하여 id값이 modal인 모달창 요소를 가져오고 이 모달창 요소의 CSS 부분에서 열기 버튼을 눌렀을 때는 display가 block으로 설정하도록 하여 처음에 display을 none으로 설정해놓았던 모달창을 등장하게 만들고 닫기 버튼을 눌렀을 때는 display을 none으로 설정하여 다시 모달창을 숨겨놓도록 하였다.

 

 

 

github.com/k0502s/javascript_modal

 

k0502s/javascript_modal

Contribute to k0502s/javascript_modal development by creating an account on GitHub.

github.com

 

반응형

댓글