背景:Ant官网有个对话框Model组件.如图:

clipboard.png

如果哪天不能用框架了,不能用组件了.只能用原生写页面.. 现在的我可能要一个页面写一年

目标:用原生js完成这个页面.弹框处于垂直居中状态,且点击弹框外任意区域关闭弹框.

写了很久很久...时间就不说了...
遇到的最难的问题就是:不知道怎么关闭弹框.
后面还是问了旁边的同事,教我用了document.querySelector()和.classList()还有addEventListener()
百度了一下它们的用法:
document.querySelector():

clipboard.png

addEventListener():

clipboard.png

classList():

clipboard.png

clipboard.png

我的理解是:先匹配对象,再设置监听器.把设置了隐藏属性的css代码添加进去.最后利用stopPropagation()方法阻止弹框冒泡.
可能理解的不是很好..大概就是这个意思...
如果有对这几个方法理解比较好的..可以留下评论给我参考一下..谢谢 - 0 -

附上最终代码和结果图:

代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>弹框和遮罩层</title>
    <style>
        .bg {
            position: fixed;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            z-index: 1000;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.45);
            text-align: end;
        }
        .point {
            position: absolute;
            width: 300px;
            height: 200px;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            background: #fff;
            border-radius:5px;
        }
        .active {
            display: none
        }
    </style>
</head>
<body>
    <div>
        <div style="color:black;text-align: center;margin: 50px 300px 300px 100px;">我是页面</div>
        <div class="bg">我是遮罩层
            <div class="point">
                <p style="padding: 10px; text-align: left">标题</p>
                <hr>
                <p style="padding: 0px 0px 0px 10px; text-align: left">今天学习原生js</p>
                <div class="pop">
                </div>
            </div>
        </div>
        <div>
</body>

<script>
    const el = document.querySelector('.bg')
    el.addEventListener('click', () => {
        el.classList.add('active')
    })
    document.querySelector('.point').addEventListener('click', (e) => {
        e.stopPropagation()
    })
</script>
</html>

  • 最终效果图:

一进页面的样子:

clipboard.png

点击除了白色弹框任意位置:

clipboard.png


Timor
37 声望21 粉丝