App下載

在Html5中怎么實(shí)現(xiàn)頁面點(diǎn)擊遮罩層背景和關(guān)閉遮罩層效果?案例分享!

有啤酒肚的仙女 2021-08-17 10:45:10 瀏覽數(shù) (3529)
反饋

今天小編來和大家分享有關(guān)于:“在Html5中怎么實(shí)現(xiàn)頁面點(diǎn)擊遮罩層背景和關(guān)閉遮罩層效果?”這個(gè)問題的相關(guān)內(nèi)容分享,希望小編的分享對(duì)大家有所幫助! 

html代碼:

頁面上只有一個(gè)展示的按鈕,一個(gè)ID為bg的div作為灰色背景遮罩層使用,ID為popup的div作為紅包彈窗,ID為close的div作為關(guān)閉按鈕。

<body>
    <div class="btn" id="btn">展示</div>
    <div class="bg" id="bg">
        <div class="popup" id="popup">
            <div class="close" id="close">X</div>
        </div>
    </div>
</body>

CSS代碼

css代碼里面沒什么技術(shù)難點(diǎn),唯一要注意的是要給灰色背景的遮罩層一個(gè)絕對(duì)定位,top和lefe都為0就好了

    body {
        position: relative;
    }
    .btn {
        width: 100px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        margin:20px auto 0;
        border: 1px solid #333;
        border-radius: 10px;
    }
    .bg {
        width: 100%;
        height: 100%;
        position: fixed;
        top: 0;
        left: 0;
        background-color: rgba(0, 0, 0, .6);
        display: none;
    }
    .popup {
        width: 260px;
        height: 320px;
        background: red;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        border-radius: 15px;
     }
    .popup .close {
        width: 30px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        position: absolute;
        top: -40px;
        right: 0px;
        border: 1px solid #999;
        border-radius: 50%;
        color: #999;
    }

JS代碼:

    var btn = document.getElementById('btn');
    var bg = document.getElementById('bg');
    var popup = document.getElementById('popup');
    var closeBtn = document.getElementById('close');
    // 點(diǎn)擊展示按鈕顯示彈窗
    btn.addEventListener('click', ()=> {
        bg.style.display = 'block';
    });
    // 點(diǎn)擊陰影遮罩層關(guān)閉彈窗
    bg.addEventListener('click', (e)=> {
        bg.style.display = 'none'
    });
    // 阻止冒泡事件,點(diǎn)擊彈窗不會(huì)執(zhí)行父元素的點(diǎn)擊事件
    popup.addEventListener('click', (e)=> {
        e.stopPropagation();
    });
    // 點(diǎn)擊關(guān)閉符號(hào)關(guān)閉彈窗
    closeBtn.addEventListener('click', (e)=> {
        e.stopPropagation();
        bg.style.display = 'none'
    })

那么今天小編和大家分享的有關(guān)于:“在Html5中怎么實(shí)現(xiàn)頁面點(diǎn)擊遮罩層背景和關(guān)閉遮罩層效果?”這個(gè)問題的相關(guān)內(nèi)容就分享到這里了!更多有關(guān)于html5這方面的相關(guān)內(nèi)容我們都可以在W3Cschool中進(jìn)行學(xué)習(xí)!


0 人點(diǎn)贊