模态框简单实现
在学bootsrap时首次接触模态框,觉得模态框非常的神奇。在bootstrap加几个类就可以搞完,模态框;
下面来自己做一个吧
总体结构:
<div class="model-box" > <!--模态框盒子-->
<button type="button" class="model-close">×</button> <!-- X 关闭模态框-->
<div class="model-head"> <!--模态框头,标题 -->
</div>
<hr >
<div class="model-content"> <!-- 内容 -->
</div>
<hr >
<div class="model-footer"> <!-- 下脚 -->
<button type="button" class="model-close model-btn-close">关闭</button>
</div>
</div>
<div class="model-overlay"></div> <!-- 全屏阴影 -->
当然还需要js,这里就直接给出全部代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style type="text/css">
.model-overlay{
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 100%;
background-color: rgb(0,0,0,0.5);
/*兼容rgb不可以用的浏览器*/
background-color:#000;
opacity: 0.5;
z-index: 10;
visibility: hidden;
}
.model-box{
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
height: auto;
width: 400px;
z-index: 11;
background-color: #fff;
box-sizing: border-box;
padding-bottom: 6px;
padding-left: 4px;
padding-right: 4px;
visibility: hidden;
}
.model-close{
border: none;
background-color: #fff;
outline: none;
font-size: 2em;
float: right;
}
.model-btn-close{
font-size: 1em;
background-color: #999;
color: #fff;
}
</style>
<body>
<input type="button" name="" id="show" value="显示模态框" /><!--模态框盒子-->
<div class="model-box" id="mymodel">
<button type="button" class="model-close">×</button>
<div class="model-head">
<h3>模态框头部</h3>
</div>
<hr >
<div class="model-content">
<h1>hello world</h1>
<h2>hello world</h2>
<h3>hello world</h3>
</div>
<hr >
<div class="model-footer">
<button type="button" class="model-close model-btn-close">关闭</button>
</div>
</div>
<div class="model-overlay"></div>
</body>
<script type="text/javascript">
window.onload=function(){
var btn=document.getElementById('show');
var model=document.getElementById('mymodel');
var overlay=document.getElementsByClassName('model-overlay')[0];
var btnClose=document.getElementsByClassName('model-close');
btn.onclick=function(){
model.style.visibility='visible';
overlay.style.visibility='visible';
}
for(var i=0;i<btnClose.length;i++){
btnClose[i].onclick=function(){
model.style.visibility='hidden';
overlay.style.visibility='hidden';
}
}
}
</script>
</html>