如何调用多个弹出窗口?

时间:2019-04-04 23:29:12

标签: javascript html css

我正在使用W3School弹出窗口,但是我很难激活多个弹出窗口。当我第二次激活时,它总是先打开。

CSS:

/* Popup container - can be anything you want */
.popup {
  position: relative;
  display: inline-block;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* 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;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  margin-left: -80px;
}

/* Popup arrow */
.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;
}

/* Toggle this class - hide and show the popup */
.popup .show {
  visibility: visible;
  -webkit-animation: fadeIn 1s;
  animation: fadeIn 1s;
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
  from {opacity: 0;} 
  to {opacity: 1;}
}

@keyframes fadeIn {
  from {opacity: 0;}
  to {opacity:1 ;}
}

HTML:

 <div class="popup" onclick="myFunction()">Click me to toggle the popup!
 <span class="popuptext" id="myPopup">A Simple Popup!</span>
 </div>

JS:

// When the user clicks on div, open the popup
function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
}

这是我两次尝试调用它的方式:

<!-- Popup 1 -->
<div class="popup" onclick="myFunction()">Click me to toggle the popup!
<span class="popuptext" id="myPopup">A Simple Popup!</span>
</div>

<!-- Popup 2 -->
<div class="popup" onclick="myFunction()">Click me to toggle the popup two!
<span class="popuptext" id="myPopupTwo">A Simple Second Popup!</span>
</div>

<script>
function myFunction() {
  var popuptwo = document.getElementById("myPopupTwo");
  popup.classList.toggle("show");
}
<script>

它没有用,所以我怎么称呼这个弹出窗口在另一个地方打开并具有不同的内容。正确的方法是什么?

1 个答案:

答案 0 :(得分:0)

我修改了myFunction以将id作为参数,这样您可以指定要切换的弹出窗口。还修复了一个轻微的语法错误var popupTwo = .....; popup.classList,因为弹出窗口为undefined并引发错误。

    <!-- Popup 1 -->
    <div class="popup" onclick="myFunction('myPopup')">Click me to toggle the popup!
    <span class="popuptext" id="myPopup">A Simple Popup!</span>
    </div>

    <!-- Popup 2 -->
    <div class="popup" onclick="myFunction('myPopupTwo')">Click me to toggle the popup two!
    <span class="popuptext" id="myPopupTwo">A Simple Second Popup!</span>
    </div>

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