如何使用 CSS 和 JavaScript 创建弹出窗口?

cssweb developmentfront end technologyjavascript

使用 CSS 和 JavaScript 创建弹出窗口,代码如下 −

示例

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      font-family: Arial, Helvetica, sans-serif;
   }
   .popUp {
      text-align: center;
      display: none;
      position: fixed;
      z-index: 1;
      padding-top: 100px;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.4);
   }
   .popupContent {
      font-size: 20px;
      font-weight: bold;
      background-color: #fefefe;
      margin: auto;
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
   }
   .close {
      color: rgb(255, 65, 65);
      float: right;
      font-size: 40px;
      font-weight: bold;
   }
   .close:hover, .close:focus {
      color: #ff1010;
      cursor: pointer;
   }
</style>
</head>
<body>
<h1>Popup Example</h1>
<button class="openPopUp">Open Popup</button>
<h2>Click on the above button to open popup</h2>
<div class="popUp">
<div class="popupContent">
<span class="close">×</span>
<p>Sample text inside popup</p>
</div>
</div>
<script>
   var popUp = document.querySelector(".popUp");
   var btn = document.querySelector(".openPopUp");
   var span = document.querySelector(".close");
   btn.addEventListener("click", () => {
      popUp.style.display = "block";
   });
   span.addEventListener("click", () => {
      popUp.style.display = "none";
   });
   window.onclick = function(event) {
      if (event.target == popUp) {
         popUp.style.display = "none";
      }
   };
</script>
</body>
</html>

输出

上述代码将产生以下输出 −

点击“打开弹出窗口”按钮后,将出现如下弹出窗口 −


相关文章