js实现在页面中点击一个按钮弹出模态框

6 篇文章 0 订阅

一、初始页面

二、 点击按钮后

三、点击“×”后,效果与图一相同。

HTML代码:


<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>模态框</title>
    <link rel="stylesheet" href="../清楚浏览器格式.css">
    <link rel="stylesheet" href="./模态框.css">
</head>

<body>
    <button class="btn">模态框</button>
    <div class="box">
        <div class="content">
            <span id="closeBtn" class="close">×</span>
            <h2>这是一个模态框!</h2>
        </div>
    </div>
    </div>
</body>

CSS代码:

/* 按钮 */
button {
    position: fixed;
    left: 0;
    top: 0;
    z-index: -1;
}

/*模态框*/
.box {
    position: relative;
    display: none;
    width: 100vw;
    height: 100vh;
    background-color: lightpink;
    opacity: 80%;
    align-items: center;
}

/*模态框内容*/
.content {
    top: 35vh;
    display: flex;
    position: relative;
    background-color: lightblue;
    opacity: 1;
    margin: auto;
    padding: 20px;
    width: 30vw;
    height: 150px;
    border-radius: 20px;

}


/*关闭按钮*/
.close {
    position: relative;
    top: -35px;
    right: -390px;
    text-align: center;
    color: #aaa;
    font-size: 28px;
    font-weight: bold;
    background-color: aliceblue;
    display: inline-block;
    width: 30px;
    height: 30px;
    line-height: 30px;
    border-radius: 50%;
}

.close:hover {
    color: black;
    cursor: pointer;
}

h2 {
    align-items: center;
    height: 150px;
    line-height: 150px;
}

 JS代码:

    <script>
        let button = document.querySelector(".btn")
        let closeBtn = document.querySelector(".close");
        let box = document.querySelector(".box");
        console.log(button, closeBtn, box);
        // 点击按钮显示模态框
        button.onclick = function () {
            box.style.display = "block";
        }
        // 点击关闭按钮隐藏模态框
        closeBtn.onclick = function () {
            box.style.visibility = "hidden";
        }
    </script>

 

 

  • 3
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

han_han__

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值