如何一次只打开一个弹出窗口?

时间:2016-09-10 16:11:40

标签: javascript css popup

使用以下代码作为示例,它目前允许同时打开两个弹出窗口。在我的现实应用程序中,我将有超过30个弹出窗口。 我希望在脚本中添加代码,以便在新的打开时关闭任何其他以前打开的弹出窗口。当我点击它自己时,我还希望能够关闭弹出窗口(就像现在一样)。这可以用" if"声明?请分享具体的例子。我不擅长创建自己的JavaScript代码,我只能复制/修改现有代码。 - 谢谢你提前!

以下是我使用的示例:

<!DOCTYPE html>
<html>
<style>
/* Popup container - can be anything you want */
.popup {
    position: relative;
    display: inline-block;
    cursor: pointer;
}

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



/* Toggle this class - hide and show the popup */
.popup .show {
    visibility: visible;
}



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

<h2>Popup</h2>

<div class="popup" onclick="myFunction1()">Click me to toggle the popup!
  <span class="popuptext" id="myPopup1">A Simple Popup!</span>
</div>
<br>
<br>
<br>
<div class="popup" onclick="myFunction2()">Click!
  <span class="popuptext" id="myPopup2">A Popup!</span>
</div>

<script>
// When the user clicks on div, open the popup
function myFunction1() {
    var popup = document.getElementById('myPopup1');
    popup.classList.toggle('show');
}

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


</script>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

在打开新的popuptext元素之前,您只需要一个从所有popuptext元素中删除show类的方法。您还可以通过使用一个函数并将一个参数传递给它来为其触发的弹出窗口消除为每个弹出元素设置单个函数的需要:

&#13;
&#13;
// When the user clicks on div, open the popup
function popup($target) {
    var popup = document.getElementById($target);
    closePopups($target);  
    popup.classList.toggle('show');
}


function closePopups($target) {
    var popups = document.getElementsByClassName('popuptext');
    for (i = 0; i < popups.length; i++) {
      if (popups[i].getAttribute('id') != $target) {
        popups[i].classList.remove('show');
        }
    }
}
&#13;
/* Popup container - can be anything you want */
.popup {
    position: relative;
    display: inline-block;
    cursor: pointer;
}

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



/* Toggle this class - hide and show the popup */
.popup .show {
    visibility: visible;
    -webkit-animation: fadeIn 1s;
    animation: fadeIn 1s;
}
&#13;
<h2>Popup</h2>

<div class="popup" onclick="popup('myPopup1')">Click me to toggle the popup!
  <span class="popuptext" id="myPopup1">A Simple Popup!</span>
</div>
<br>
<br>
<br>
<div class="popup" onclick="popup('myPopup2')">Click!
  <span class="popuptext" id="myPopup2">A Popup!</span>
</div>
&#13;
&#13;
&#13;