javascript - 在弹出窗口中使用图标添加关闭按钮

标签 javascript html css

我是 HTML、CSS 的新手...我正在创建一个自定义弹出窗口并且它工作正常,但我希望能够使用图标关闭弹出窗口。

您可以在下面找到我的代码。我的自定义弹出窗口只是在此弹出窗口的右上角添加了一个十字图标。

/* Popup container - can be anything you want */

.popup {
  position: relative;
  display: inline-block;
}


/* The actual popup */

.popup .popuptext {
  visibility: hidden;
  width: 160px;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 8px 0;
  position: absolute;
  left: 50%;
  margin-left: -80px;
  margin-top: 10px;
}

.popup .show {
  visibility: visible;
  -webkit-animation: fadeIn 1s;
  animation: fadeIn 1s;
}
<!DOCTYPE html>
<html>

<head>
</head>

<body style="text-align:center">

  <h2>Popup</h2>
  <a href="#" onclick="myFunction()">Click</a>
  <div class="popup">
    <span class="popuptext" id="myPopup">
       <input type="text" size="16"/>
      </span>
  </div>
  <script>
    // When the user clicks on div, open the popup
    function myFunction() {
      var popup = document.getElementById("myPopup");
      popup.classList.toggle("show");
    }
  </script>
</body>

</html>

最佳答案

首先,您需要添加关闭图标并在关闭 X 图标上调用相同的 toggle 函数:

// When the user clicks on div, open the popup
function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
}
/* Popup container - can be anything you want */

.popup {
  position: relative;
  display: inline-block;
}
.close{
   cursor:pointer;
text-align:right;
display:block;
padding:10px;
}

/* The actual popup */

.popup .popuptext {
  visibility: hidden;
  width: 160px;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 8px 0;
  position: absolute;
  left: 50%;
  margin-left: -80px;
  margin-top: 10px;
}

.popup .show {
  visibility: visible;
  -webkit-animation: fadeIn 1s;
  animation: fadeIn 1s;
}
<!DOCTYPE html>
<html>

<head>

</head>

<body style="text-align:center">

  <h2>Popup</h2>
  <a href="#" onclick="myFunction()">Click</a>
  <div class="popup">

    <div class="popuptext" id="myPopup">
      <span class="close" onclick="myFunction()">X</span>
      <input type="text" size="16" />
    </div>
  </div>

</body>

</html>

关于javascript - 在弹出窗口中使用图标添加关闭按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56216219/

相关文章:

javascript - 为什么替换方法不适用于 JavaScript 中的变量

javascript - 如何在 tsc 从 .js 文件生成的类型定义中包含继承的属性?

javascript - 如何用子div屏蔽父div?

javascript - 如何使用navigator.app.exitApp()?

javascript - 根据 dd/mm/yyyy 日期格式的出生日期计算年龄

javascript - 如何使用 window-width 改变 href

javascript - 如何使用从已有样式组件扩展的样式组件?

javascript - 是否可以从不同页面添加到 bootstrap 4 nav-pills 选项卡面板的链接?

javascript - 从不同的 HTML 页面调用方法

html - 第二个 `li` 列中的第一个 `ul` 元素没有边距?