手寫彈出框代碼詳解


1.代碼
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
    <style>
        .cover{
            position: fixed;
            /*首先將位置固定住*/
            top:0;
            right:0;
            bottom:0;
            left:0;
            /*上下左右設置都為0*/
            background-color: rgba(0,0,0,0.2);

            z-index:99;
            /*指定一個元素的堆疊順序,數值越大,表示在越上邊*/
        }
        .modal{
            width:700px;
            height:400px;
            position: absolute;
            top:50%;
            left:50%;
            margin-left: -350px;
            margin-top: -200px;
            background-color: white;
            z-index: 100;
            /*將x的位置移動*/
        }
        .close{
            float: right;
            /*在這里將x移動到右上角*/
            margin-right: 15px;
            margin-top: 10px;
            font-size: 16px;
        }
        .hide{
            display: none;
            /*表示不顯示*/
        }
    </style>
</head>
<body>

<button id="b1">點我彈出</button>

<div class="cover hide" ></div>
<!--這個標簽通過設置CSS樣式,將button及下層的東西蓋住,比如注冊登錄窗口的彈出就需要這個-->
<!--hide表示不顯示這個div標簽,注意這個hide寫在class里邊-->

<div class="modal hide" >
    <span class="close" id="s1">&times;</span>
    <!--&times;表示x的意思,也可以直接寫x-->
</div>

<script>
    // 思考如何實現,在點擊彈出按鈕之后,彈出兩個標簽
    //首先,找標簽,注意這個地方是通過id處理的
    var b1Ele=document.getElementById('b1')
    //其次,處理事件,單擊button之后,找到類屬性,移除類列表中的隱藏屬性
    b1Ele.onclick=function (ev) {
        document.getElementsByClassName('cover')[0].classList.remove('hide');
        document.getElementsByClassName('modal')[0].classList.remove('hide');
    //移除樣式
    }

        var s1Ele=document.getElementById('s1')
        //其次,處理事件,單擊button之后,找到類屬性,添加類列表中的隱藏屬性
        s1Ele.onclick=function (ev) {
        document.getElementsByClassName('cover')[0].classList.add('hide');
        document.getElementsByClassName('modal')[0].classList.add('hide');
    //移除樣式
    }
</script>
</body>
</html>
<!--目的就是:一點添加,一點關閉,這樣的操作-->

代碼效果:

(1)運行

(2)點擊"點我彈出",結果如下圖

(3)再點擊x,回到界面(1)的效果,可以反復嘗試


免責聲明!

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



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