html、css和js原生寫一個模態彈出框,順便解決父元素半透明子元素不透明效果


模態框:

html部分:

<!-- 按鈕 -->
    <button id="box" onclick="pop_box()">彈出框</button>
    <!-- 彈出模態框 -->
    <div class="div-container" id="div-container" style="display: none;">
        <div class="div-child-container">
            <div class="div-child">
                <span>hhhhh</span>
                <div class="my-btn">
                    <button id="cancleBtn" onclick="cancle()">取消</button>
                    <button id="confrim" onclick="confrim()">確認</button>
                </div>
            </div>
        </div>
    </div>

css部分:

<style type="text/css">
        #box{
            width: 80px;
            height: 40px;
            background: #fd7430;
            border:none;
            border-radius: 5px;
            outline: none;
            color: #fff;
        }

        .div-container{
            position: fixed;
            top: 0%;
            width: 100%;
            height: 100%;
            z-index:200;
            background: rgba(0,0,0,0.5) !important;/* 兼容ie幾不知道,好像ie5 */
            background:#000;
            filter:Alpha(opacity=60);
        }
        /*設置div-child的父元素主要是將要此元素的父元素透明特性繼承過來,故div-child不會半透明,而是不透明,解決了父元素透明,子元素也透明的bug */
        .div-child-container{
            position: relative;
            width: 400px;
            height: 200px;
            margin: auto;
            top: 30%;
            background: #fff;
            z-index: 250; /*z-index要放在父元素之上 */
        }

        .div-child{
            width: 400px;
            height: 200px;
            margin: auto;
            background: #fff;
            z-index: 300; /*z-index要放在父元素之上 */
            text-align: center;
        }

        .div-child span{
            position: relative;
            top: 40px;
        }

        .div-child .my-btn{
            margin-top: 80px;
        }
        .div-child .my-btn button{
            width: 80px;
            height: 40px;
            background:#fd7430;
            border: none;
            border-radius: 5px;
            color: #fff;
            outline: none;
        }

        .div-child .my-btn button:first-child(){
            margin-right: 20px;
        }
    </style>

JavaScript:

<script type="text/javascript">
        /*按鈕彈出模態框*/
        function pop_box(){
            var container = document.getElementById('div-container');
            container.style.display="block";
        }

        /*取消事件*/
        function cancle(){
            var container = document.getElementById('div-container');
            container.style.display="none";
        }

        /*確認事件,因為現在沒有確認事件,就將彈出框隱藏*/
        function confrim(){
            var container = document.getElementById('div-container');
            container.style.display="none";
        }
    </script>

 

 

如有疑問,可留言!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM