以下面的代码为例,当前它允许两个弹出窗口同时打开。在我的实际应用程序中,我将有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>
show
在打开新的popuptext元素之前,您只需要一种从所有popuptext元素中删除该类的方法即可。您还可以通过使用一个函数并将参数传递给要触发的弹出窗口,从而消除每个弹出窗口元素都具有单个函数的需要:
// 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');
}
}
}
/* 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;
}
<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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句