最近需要写一个自定义的弹框,之前的弹框是用的alert()或者confirm(),满足不了需求因此重新写一个自定义的。
写弹框我想到了在写一个遮罩层会使得效果更好,今天在这里做个笔记以后用到的时候方便自己。
遮罩实现的原理:
写一个div定义他的宽高和屏幕相同然后设置他的z-index值使得他位于其他层上面。
详情见下面代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>遮罩层实现</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<script src="js/jquery-1.11.0.min.js"></script>
<style>
<!--
弹框样式
-->
#tk{
width:70%;
height:220px;
background:white;
position: absolute;
top:30%;
left:15%;
display: block;
z-index:1200;
}
#tk .tit{
width:100%;
height:40px;
border-bottom: 1px solid #000000;
}
.tk-word{
width:60%;
height:100%;
display:inline-block;
text-align: center;
line-height: 40px;
font-size: 20px;
font-weight: 800;
margin-left:20%;
}
.tk-close{
width:20px;
display: block;
float:right;
margin-top: 10px;
margin-right:4px;
}
.tk-close{
width:20px;
display: block;
float:right;
margin-top: 10px;
margin-right:4px;
}
.tk-body{
width:80%;
margin-left:10%;
margin-top:10px;
text-indent:2em;
line-height:22px;
font-size: 18px;
}
.tk-foot{
width:100%;
height:50px;
margin-top:14px;
}
.tk-foot-xq{
margin: 10px auto;
display: block;
width: 62%;
height: 44px;
background: #7cd6ef;
color: #fff;
font: bold 16px/44px '微软雅黑';
border-radius: 10px;
padding: 0 10px;
text-align: center;
}
<!--
遮罩样式
-->
.shadow{
width:100%;
height:100%;
position:absolute;
left:0;
top:0;
z-index:998;
background-color:#000;
opacity:0.6;
display:block;
</style>
</head>
<body>
<!--
弹框
-->
<div id="tk">
<div class="tit">
<span class="tk-word">重要通知</span>
<img class="tk-close" src="images/close.jpg" alt="">
</div>
<div class="tk-body">
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
</div>
<div class="tk-foot">
<a href="buchong/bcinfor.html?tjid=6" class="tk-foot-xq">查看详情</a>
</div>
</div>
<!--
遮罩
-->
<div class="shadow"></div>
</body>
//遮罩层显示时禁止页面滚动
$('.shadow,#tk').bind("touchmove",function(e){
e.preventDefault();
});
//关闭弹框时同时关闭遮罩层
$('.tk-close').click(function(){
//console.log(111);
$('#tk').css('display','none');
$('.shadow').css('display','none');
})
</html>
在遮罩层实现后发现一个bug,遮罩层下面的页面高度大于屏幕高度,多以页面可以滑动这样就破坏了遮罩层;
解决方案:在js中加入以下方法去除遮罩层和按钮层的touchmove的默认事件:
//去除遮罩层和按钮层的touchmove的默认事件(移动端专用)
$('.shadow,#tk').bind("touchmove",function(e){
e.preventDefault();
});
这是移动端解决方案,因为没写pc页面所以百度了一下解决pc的方法:
pc端的解决思路就是在弹出遮罩层的时候取消已经存在的滚动条,达到无法滚动的效果。
也就是说给body添加overflow:hidden属性即可,IE6、7下不会生效,需要给html增加overflow:hidden属性。