使用 JavaScript怎么在实现一个模态框

这篇文章将为大家详细讲解有关使用 JavaScript怎么在实现一个模态框,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

html部分:

<img src="images/8.jpg" alt="">
 <button class="btn" id="showMax">显示大图</button> 
 <div id="modalBox" class="modalBox">
 <div class="modalBox-matter">
  <header class="modalBox-header">
   <span class="mtclose">×</span>
  </header> 
  <div class="modalBox-body">

    <img src="images/8-1.jpg">

  </div>
 </div>
</div>

js部分:

var btn = document.getElementById('showMax'); 
 var mtclose = document.getElementsByClassName('mtclose')[0];
 var modalBox = document.getElementById('modalBox'); 
 btn.addEventListener('click', function(){ 
  modalBox.style.display = "block"; 
 }); 
 mtclose.addEventListener('click', function(){ 
  modalBox.style.display = "none"; 
 });

css部分:

.btn{ 
 width: 100px; 
 height: 35px; 
 border-radius: 5px; 
 font-size: 16px; 
 color: #F97B39;

 position: absolute;
 top: 130px;
 left: 160px;
 opacity: 0.2;
 cursor: pointer; /*鼠标小手*/
} 

.btn:hover, .btn:focus{ /*focus 取得焦点状态*/
 background-color: #8AA7F9;
 opacity: 0.5;
 color: #FFFFFF;
} 
.modalBox{ 
 display: none; 
 width: 100%; 
 height: 100%; 
 position: fixed; 
 left: 0; 
 top: 0; 
 z-index: 1000; 
 background-color: rgba(0,0,0,0.5);
}

.modalBox-matter{ 
 display: flex;    /*/*弹性布局*/
 flex-flow: column nowrap; 
 justify-content: space-between;     /*两端对齐*/
 width: 50%; 
 height: 80%;
 margin: 30px auto 100px; 
 border-radius:10px;
 -webkit-animation: zoom 0.6s; 
 animation: zoom 0.6s; 
 resize: both; 
 overflow: auto; 
}

@keyframes zoom{ 
 from {transform: scale(0)} 
 to {transform: scale(1)} 
}

.modalBox-header{

  margin-left: 617px; 
}

.mtclose{
 color: #602E2A; 
 font-size: 3em; 
 font-weight: bold; 
 transition: all 0.3s;
 /*z-index: 1010; */
 } 
 .mtclose:hover, .mtclose:focus{ 
 color: #602E2A; 
 cursor: pointer; 
}

.modalBox-body{ 
 padding: 10px; 
 font-size: 16px; 
}

关于使用 JavaScript怎么在实现一个模态框就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。