原生JavaScript练习——弹出层

HTML:

<button id="pop">登录</button>
    <div id="wrap"></div>
    <div id="box">
        <h3>我是弹出层(づ。◕‿‿◕。)づ</h3>
    </div>

CSS:

#wrap {
            background: #000;
             100%;
            height: 100%;
            position: absolute;
            top: 0;
            left: 0;
            opacity: 0.4;
            filter: alpha(opacity = 40);
            z-index: 100; 
            display: none;
        }
        #box {
             400px;
            height: 300px;
            background: pink;
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            margin: auto;
            display: none;
            z-index: 101;  
        }
        #box h3 {
            text-align: center;
            line-height: 250px;
        }

其中这段代码可以让登录框处于页面的中央位置,可跟随页面的大小发生改变。

            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            margin: auto;

Javascript:

var pop = document.getElementById('pop'),
     wrap = document.getElementById('wrap'),
     box = document.getElementById('box');

// 弹出层
            pop.onclick = function () {
                wrap.style.display = 'block';
                box.style.display = 'block';
            };

// 关闭弹出层
            wrap.onclick = box.onclick = function () {
                wrap.style.display = 'none';
                box.style.display = 'none';
            }

其中使用“=”符号可以使两个事件共用同一种方法。

原文地址:https://www.cnblogs.com/luohaoran/p/5919403.html