遮罩层:
又名弹出框,是一种页面在常用不过的效果之一了,今天就说一说这一效果的制作原理:
代码展示
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{margin:0px;padding:0px;}
</style>
<link rel="stylesheet" href="shadowxx.css" />
<script src="jquery-1.7.2.js"></script>
<script src="shadowxx.js"></script>
<script>
$(function(){
$('.btn').on('click',function(){
shadow({
title:'大兄弟',
closeText:'确定2',
cancel:false,
beforeConfirm:function(){
alert('确定之前');
},
afterConfirm:function(){
alert('确定之后');
},
},$('.shadow'));
})
})
</script>
</head>
<body>
<div class="btn">123</div>
<div class="shadow"></div>
</body>
</html>
css:
/*弹出框*/
.shadow{display: none;}
.shadowxx{100%;height:100%;background-color:rgba(0,0,0,0.4);position: fixed;left:0px;top:0px;z-index:999;}
.shadowxx .promptxx{300px;height:auto;position:relative; top:50%;background: #fff; margin: 0 auto; transform:translate(0%,-50%);border-radius:6px;padding-bottom:20px;}
.shadowxx .promptxx .titlexx{padding-top:20px;font-size:22px;text-align: center;line-height:50px;}
.shadowxx .promptxx .btnxx{font-size:16px;text-align: center;color:#fff;margin:30px auto;margin-bottom:0px;}
.shadowxx .promptxx .btnxx div{display: inline-block;100px;height:30px;line-height:30px;border-radius:6px;cursor:pointer;}
.shadowxx .promptxx .btnxx .confirmxx{background: #f14848;}
.shadowxx .promptxx .btnxx .cancelxx{background: #f14848;margin-right:20px;}
js:
function shadow(json,parent){ json=json||{}; json.title=json.title; //内容 json.closeText=json.closeText || '确定'; //确定按钮的内容 json.cancel=json.cancel || false; //取消按钮是否存在 json.beforeConfirm=json.beforeConfirm || null;//确定之前 json.afterConfirm=json.afterConfirm || null;//确定回调 json.beforeCancel=json.beforeCancel || null;//取消之前 json.afterCancel=json.afterCancel || null;//取消回调 //创建弹出框 var str= '<div class="shadowxx">'+ '<div class="promptxx">'+ '<div class="titlexx">5555555</div>'+ '<div class="btnxx">'+ '<div class="cancelxx">取消</div>'+ '<div class="confirmxx">'+json.closeText+'</div>'+ '</div>'+ '</div>'+ '</div>'; parent.html(str); //取消显示隐藏 if(json.cancel){ $('.cancelxx').css({ 'display':'inline-block' }); }else{ $('.cancelxx').css({ 'display':'none' }); } //确定按钮 $('.shadowxx').on('click','.confirmxx',function(){ json.beforeConfirm&&json.beforeConfirm(); parent.hide(function(){ json.afterConfirm&&json.afterConfirm();//确定之后回调 }); }); //取消按钮 $('.shadowxx').on('click','.cancelxx',function(){ json.beforeCancel&&json.beforeCancel(); parent.hide(function(){ json.afterCancel&&json.afterCancel();//取消之后的回调 }); }); var clientHeight=$(window).height(); var clientWidth=$(window).width(); parent.css({ 'position':'absolute', 'top':0, 'left':0, 'width':clientWidth, 'height':clientHeight, }); parent.show(); }
知识点总结:
1.shadowxx是黑色透明,底层的透明层;width,height是整个可视区,而且层级要提到最高,它的层级高了,它的子级的层级比它高;
2.promptxx是显示在中间的内容,绝对定位,left:50%,top:50%,transform:translate(-50%,-50%);
3.在页面创建一个空div(“.shadow”)用于放置遮罩层;
4.对于创建出来的东西要使用事件委托来处理;
创建一个遮罩层需要三层包裹哦!!!