You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

弹窗功能优化问询:遮罩关闭、ESC关闭、自适应高度与居中

弹窗优化实现方案

优化点说明

1. 点击遮罩关闭弹窗

给.ourOverlay元素绑定点击事件,触发弹窗切换函数,点击遮罩区域时自动关闭弹窗。

2. ESC键关闭弹窗

添加键盘事件监听,当弹窗处于激活状态时,按下ESC键触发弹窗关闭逻辑,同时在弹窗关闭时移除监听避免无效触发。

3. 内容高度自适应

移除.ourContent的固定height属性,让容器高度随内部内容自动撑开;可按需添加min-height保证弹窗的最小显示高度。

4. 固定在屏幕中央

将.ourContent的定位属性从absolute改为fixed,使其相对于浏览器视口定位,完全不受父元素位置影响,始终保持在屏幕中央。


修改后的完整代码

HTML
<html lang="en">
<head>
  <title>Simple Popup Box / Modal </title>
</head>
<body>
  <div class="ourPopUp" id="myPopUp-1">
    <div class="ourOverlay" onclick="togglePopUp()"></div>
    <div class="ourContent">
      <div class="ourClose-btn" onclick="togglePopUp()">&times;</div>
      <h1>Simple Popup Box / Modal using HTML CSS & JavaScript</h1>
      <p>A simple popup box / modal using HTML CSS and JavaScript.</p>
      <!-- 可添加更多内容测试高度自适应效果 -->
      <!-- <p>额外测试内容,验证容器高度是否会自动跟随内容调整...</p> -->
    </div>
  </div>
  <button onclick="togglePopUp()">Show Popup</button>
</body>
</html>
CSS
.ourPopUp .ourOverlay {
  position: fixed;
  top: 0px;
  left: 0px;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.7);
  z-index: 1;
  display: none;
}

.ourPopUp .ourContent {
  position: fixed; /* 改为fixed定位,基于视口居中 */
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) scale(0);
  background: #fff;
  width: 450px;
  min-height: 220px; /* 保留最小高度,可根据需求调整或移除 */
  z-index: 2;
  text-align: center;
  padding: 20px;
  box-sizing: border-box;
}

.ourPopUp .ourClose-btn {
  cursor: pointer;
  position: absolute;
  right: 20px;
  top: 20px;
  width: 30px;
  height: 30px;
  background: #222;
  color: #fff;
  font-size: 25px;
  font-weight: 600;
  line-height: 30px;
  text-align: center;
  border-radius: 50%;
}

.ourPopUp.active .ourOverlay {
  display: block;
}

.ourPopUp.active .ourContent {
  transition: all 300ms ease-in-out;
  transform: translate(-50%, -50%) scale(1);
}
JavaScript
function togglePopUp() {
  const popup = document.getElementById("myPopUp-1");
  popup.classList.toggle("active");
  
  // 根据弹窗状态动态添加/移除ESC键监听
  if (popup.classList.contains("active")) {
    document.addEventListener("keydown", handleEscKey);
  } else {
    document.removeEventListener("keydown", handleEscKey);
  }
}

// ESC键触发关闭逻辑
function handleEscKey(e) {
  if (e.key === "Escape") {
    togglePopUp();
  }
}

内容的提问来源于stack exchange,提问作者Lotus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 17:48:19