之前工作中经常用到模态框,早就想总结一下可苦于一直没有时间,今天忙里偷闲小结如下:
这里只是一个最简单的模态框哦~~
先看一下效果吧:
因为实在是太简单了 所以还是直接上代码吧
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
body {
font-family: "微软雅黑";
padding: 0px;
margin: 0px;
}
a {
text-decoration: none;
color: #333;
}
.trigger {
display: inline-block;
margin: 100px 400px;
}
/*----------模态框样式开始-----------*/
.modalBox {
display: none;
}
.overLay {
position: fixed;/*这里的定位方式使用fixed能保证遮罩层百分百的覆盖整个窗口*/
width: 100%;
height: 100%;
top: 0;
left: 0;
opacity: 0.5;
background-color: #000000;
}
.alertContent {
width: 200px;
height: 200px;
background: #ffffff;
border: 1px solid #333333;
position: absolute;
top: 200px;
left: 500px;
}
.alertContent p {
border-bottom: 1px dashed #333333;
}
</style>
</head>
<body>
<a class="trigger" href="javascript:;">点我 点我!!!</a>
<div class="modalBox">
<div class="overLay"></div>
<div class="alertContent">
<p>Title</p>
<div>Content</div>
</div>
</div>
<script>
var trigger = document.getElementsByTagName("a")[0];
var modal = document.getElementsByClassName("modalBox")[0];
trigger.onclick = function (){
modal.style.display = 'block';
}
</script>
</body>
这里有一个问题需要注意!!!
遮罩层overLay的定位方式为什么不用absolute而是使用fixed。我之前也是使用absolute一直没有问题,可是突然有一天不知道什么原因遮罩层不能完全覆盖整个页面了。后来想到可以使用fixed,因为fixed定位是相对于浏览器窗口的所以能保证百分百的覆盖浏览器窗口!