JS来添加弹出层,并且完成锁屏

上图

<html>
<head>
    <title>弹出层</title>
    <style type="text/css">
        *{
            padding:0px;
            margin:0px;
        }
        .up{
            500px;
            height: 400px;
            border:1px solid silver;
            position: absolute;
            display: none;
            z-index: 9999;
            background:#fff;
/*            top:50%;
            left: 50%;*/
/*            margin-left: -250px;
            margin-top: -200px;*/
        }
        .up h2{
            background-color: #f2f2f2;
            text-align: center;
        }
        .con span{
            20px;
            height:30px;
            text-align: center;
            line-height: 30px;
            background-color:red;
            cursor: pointer;
        }
        .mask{
            3000px;
            height: 3000px;
            background:#000;
            opacity: 0.3;
            position: absolute;
            top:0;
            left: 0;
            z-index: 9998;
            display:none;
        }
    </style>
</head>
<body>
    <div class="con">
        <span id="open">打开弹出层</span>
    </div>
    <div class="up" id="up">
            <h2>弹出层效果</h2>
            <span id="close">关闭</span>
    </div>
    <img src="a.jpg">

</body>
<script type="text/javascript">
//两种方式实现div居中:1:用css方式:top:50%,left:50%; margin-let:-divwidth/2 margin-top:divheight/2; 2:用js实现:获取窗口的高宽,top=(屏幕高-div高)/2,为了随时的监听浏览器的改变,需要用到浏览器事件

    window.onload=function(){
        function $(id){
            return document.getElementById(id);
        }
        //将div的位置封装在一个函数内部,直接调用
        function myDiv(){
            var mTop=(document.documentElement.clientHeight-500)/2;
            var mleft=(document.documentElement.clientWidth-400)/2;
            $("up").style.top=mTop+"px";
            $("up").style.left=mleft+"px";
        }
         myDiv();
         $("open").onclick=function(){
             $("up").style.display="block";
             mask.style.display="block";
             
         }
          $("close").onclick=function(){
             $("up").style.display="none";
             mask.style.display="none"
         }
         //创建一个DIV
         var mask=document.createElement("div");
         // //给这个DIV一个id和class属性
         // mask.id="mask";
         mask.className="mask";
         mask.style.width=document.documentElement.clientWidth;
         mask.style.height=document.documentElement.clientHeight;
         //将这个DIV放置到body里面--》一般是:父节点.appendChild(子节点)
         //这里注意的是absolute,要设置top和left;
         document.body.appendChild(mask); 
         
        //屏幕改变大小的时候,div不会自动的改变,需要添加窗口改变事件
        window.onresize=function(){
             myDiv();
             mask.style.width=document.documentElement.clientWidth;
             mask.style.height=document.documentElement.clientHeight;
        }
    }
</script>
</html>
原文地址:https://www.cnblogs.com/allenxieyusheng/p/6065568.html