今天小编来和大家分享有关于:“在Html5中怎么实现页面点击遮罩层背景和关闭遮罩层效果?”这个问题的相关内容分享,希望小编的分享对大家有所帮助! 

html代码:

页面上只有一个展示的按钮,一个ID为bg的div作为灰色背景遮罩层使用,ID为popup的div作为红包弹窗,ID为close的div作为关闭按钮。

<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代码里面没什么技术难点,唯一要注意的是要给灰色背景的遮罩层一个绝对定位,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');
    // 点击展示按钮显示弹窗
    btn.addEventListener('click', ()=> {
        bg.style.display = 'block';
    });
    // 点击阴影遮罩层关闭弹窗
    bg.addEventListener('click', (e)=> {
        bg.style.display = 'none'
    });
    // 阻止冒泡事件,点击弹窗不会执行父元素的点击事件
    popup.addEventListener('click', (e)=> {
        e.stopPropagation();
    });
    // 点击关闭符号关闭弹窗
    closeBtn.addEventListener('click', (e)=> {
        e.stopPropagation();
        bg.style.display = 'none'
    })

那么今天小编和大家分享的有关于:“在Html5中怎么实现页面点击遮罩层背景和关闭遮罩层效果?”这个问题的相关内容就分享到这里了!更多有关于html5这方面的相关内容我们都可以在W3Cschool中进行学习!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。