如果您打开另一个弹出窗口,请关闭打开的弹出窗口

时间:2018-08-21 07:58:21

标签: html css user-interface popup frontend

嘿,我做了几个弹出窗口。要关闭弹出窗口,请按打开的弹出窗口。如果您打开一个新的弹出窗口,那么我想关闭另一个出现的弹出窗口。

  

例如,如果我打开一个弹出窗口1.然后我打开了弹出窗口2,那么当弹出窗口2打开时,弹出窗口1关闭了

这是我的html代码

<body style="text-align:center">
<br><br><br>
<div class="popup" onclick="popUp1()">Click me!
  <span class="popuptext" id="myPopup1">Popup 1</span>
</div>
&nbsp; &nbsp; &nbsp;
<div class="popup" onclick="popUp2()">Click me!
  <span class="popuptext" id="myPopup2">Popup 2</span>
</div>

&nbsp; &nbsp; &nbsp;
<div class="popup" onclick="popUp3()">Click me!
  <span class="popuptext" id="myPopup3">Popup 3</span>
</div>

<script>
function popUp1() {
    var popup = document.getElementById("myPopup1");
    popup.classList.toggle("show");
}

function popUp2() {
    var popup = document.getElementById("myPopup2");
    popup.classList.toggle("show");
}

function popUp3() {
    var popup = document.getElementById("myPopup3");
    popup.classList.toggle("show");
}
</script>

</body>

这是我的css

.popup {
  position: relative;
  display: inline-block;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}    
.popup .popuptext {
  visibility: hidden;
  width: 160px;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 8px 0;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  margin-left: -80px;
}
.popup .popuptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}    
.popup .show {
  visibility: visible;
  -webkit-animation: fadeIn 1s;
  -moz-animation: fadeIn 1s;
  -ms-animation: fadeIn 1s;
  animation: fadeIn 1s;
}    
@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity:1 ; }
}

谢谢

2 个答案:

答案 0 :(得分:0)

您需要一个JavaScript函数来执行此操作,例如:

 $('.popup').on('click', function() {
      $('.popup').each(function(i, elem){
          if ($(elem).hasClass('show') && this !== elem ) {
                $(elem).removeClass('show');
          }
      });
 });

答案 1 :(得分:0)

我将尝试使用纯JavaScript进行解释,因为您没有像其他答复那样使用jQuery。

此代码应删除所有具有show类的弹出窗口,并将show类添加到触发事件的那个弹出窗口。

   function closeOpenPopups (e) {
    var openpopups = document.querySelectorAll('.popup.show');
     openpopups.forEach(function(){
      this.classList.remove('show');
     });
      e.classList.add('show');
    }
    var popups = document.querySelectorAll('.popup');

您可以像在HTML上一样将其添加到onclick属性中

<div class="popup" onclick="closeOpenPopups()" >
 ...
</div>

希望有帮助,