美文网首页js高级
原生js实现遮罩层

原生js实现遮罩层

作者: 令狐张豪 | 来源:发表于2019-08-05 20:59 被阅读2次
    <!-- 遮罩层 -->
    <div id="mask"></div>

    <button id="btn">单机显示遮罩层</button>

    <!-- 弹出框 -->
    <div class="box">
        <span class="close">&times;</span>
        <p>单机显示遮罩层</p>
    </div>


</body>

css样式设置

    html * {
        margin: 0;
        padding: 0;
    }

    /* 遮罩层样式设置 */
    #mask {
        width: 100%;
        height: 100%;
        position: absolute;
        /* 给遮罩层绝对定位 */
        z-index: 10;
        /* 设置z-index值(要小于弹出框) */
        background-color: rgba(0, 0, 0, 0.65);
        /* opacity: 0.5; */
        /* 设置 div 元素的不透明级别 */
        display: none;
    }

    /* 设置弹出框样式 */
    .box {
        width: 300px;
        height: 200px;
        position: fixed;
        left: 50%;
        top: 50%;
        margin-top: -100px;
        margin-left: -150px;
        z-index: 30;
        /* 设置z-index值(要大于遮罩层) */
        box-shadow: 2px 2px 4px #ccc;
        background-color: #f1f1f1;
        border: 1px solid #aaa;
        border-radius: 4px;
        overflow: hidden;
        display: none;
    }

    .box span {
        float: right;
        cursor: pointer;
    }

    .box p {
        color: red;
    }
</style>

JS代码

    window.onload = function () {
        btn.onclick = function () {
            document.getElementsByClassName('box')[0].style.display = "block"
            mask.style.display = "block"
        }
        document.getElementsByClassName('close')[0].onclick = function () {
            document.getElementsByClassName('box')[0].style.display = "none"
            mask.style.display = "none"
        }
    }
</script>

相关文章

网友评论

    本文标题:原生js实现遮罩层

    本文链接:https://www.haomeiwen.com/subject/gnpvdctx.html