原生js创建模态框

1.效果图如下:

1

2.代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<style>
    #pageMask {
        visibility: hidden;    
        position: absolute;
        left: 0px;    
        top: 0px;
        width:100%;
        height:100%;
        text-align: center;
        z-index: 1100;
        background-color: #333; 
        opacity: 0.6;
    }
    #ModalBody{
        background: white;
        width: 50% !important;
        height: 50% !important;
        position:absolute;
        left: 25%;
        top: 25%;
        z-index: 1101;
        border: 1px solid;
        display: none;
    }
    #closeModalBtn{
        position: static;
        margin-top: 5px;
      margin-right: 1%;
      float: right;
        font-size: 14px;
        background: #ccc0;
        cursor: pointer;
    }
</style>
</head>
<body>
    <div class="content">
        <h1>Test Modal</h1>
        <div id="pageMask"></div>     <!--遮盖层-->
        <button class="showModalBtn" id="showModalBtn">Btn</button>
        <div>    <!--主页面-->
            Page Content...
        </div>
    </div>
    
    <div id="ModalBody">    <!--模态框-->
        <button id="closeModalBtn" style="display: none;">Close</button>
        <div>Test Modal Body...</div>
    </div>
    
    <script>
        window.onload = function(){
            expandIframe();
        }
        function expandIframe(){
            var mask = document.getElementById("pageMask");
            var modal = document.getElementById("ModalBody");
            var closeBtn = document.getElementById("closeModalBtn");
                    var btn = document.getElementById("showModalBtn");
            
            btn.onclick = function(){
                modal.style.display = (modal.style.display == "block")? "none" : "block";
                closeBtn.style.display = (closeBtn.style.display == "block")? "none" : "block";
              mask.style.visibility = (mask.style.visibility == "visible")? "hidden" : "visible";
            }
            
            closeBtn.onclick = function(){
                modal.style.display = (modal.style.display == "block")? "none" : "block";
                closeBtn.style.display = (closeBtn.style.display == "block")? "none" : "block";
                mask.style.visibility = (mask.style.visibility == "visible")? "hidden" : "visible";
            }
        }
    </script>
</body>
</html>
posted @ 2018-05-23 14:57  东窗凝残月  阅读(791)  评论(0编辑  收藏  举报