我在使用这段代码时遇到了一些麻烦。我知道,至少到目前为止,弹出窗口将在选择文本时显示。问题是我不能让它全部4工作,所以我得到4个不同的弹出窗口,所有弹出窗口都连接到第一个。我也试图得到它,以便点击每个按钮下的弹出窗口。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.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: -250%;
left: 50%;
margin-left: -80px;
}
.popup .show {
visibility: visible;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s;
}
</style>
</head>
<body style="text-align:center">
<div class="popup" onclick="myFunction()">First Popup
<span class="popuptext" id="myPopup">This is the first pop up selected</span>
</div>
<div class="popup" onclick="myFunction()">second Popup
<span class="popuptext" id="myPopup">This is the second pop up selected</span>
</div>
<div class="popup" onclick="myFunction()">third Popup
<span class="popuptext" id="myPopup">This is the third pop up selected</span>
</div>
<div class="popup" onclick="myFunction()">Fourth Popup
<span class="popuptext" id="myPopup">This is the fouth pop up selected</span>
</div>
<script>
function myFunction() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}
</script>
</body>
</html>
我的问题是如何才能让弹出窗口在每个文本下正确显示?
谢谢。
答案 0 :(得分:0)
您为每个弹出窗口使用了相同的ID。你不能这样做。每个弹出窗口都需要有唯一的ID。
答案 1 :(得分:0)
ID是唯一选择器。相反,你必须为你的目的使用类名。
另外,要确定您点击了哪个弹出式标题,可以使用event.currentTarget
function myFunction(event) {
const currentlyVisible = document.querySelector('.popup .show');
if(currentlyVisible) {
currentlyVisible.classList.toggle('show');
}
var popup = event.currentTarget.querySelector('.popuptext');
popup.classList.toggle("show");
}
&#13;
body {
text-align: center;
}
.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: -250%;
left: 50%;
margin-left: -80px;
}
.popup .show {
visibility: visible;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s;
}
&#13;
<div class="popup" onclick="myFunction(event)">First Popup
<span class="popuptext" >This is the first pop up selected</span>
</div>
<div class="popup" onclick="myFunction(event)">second Popup
<span class="popuptext">This is the second pop up selected</span>
</div>
<div class="popup" onclick="myFunction(event)">third Popup
<span class="popuptext">This is the third pop up selected</span>
</div>
<div class="popup" onclick="myFunction(event)">Fourth Popup
<span class="popuptext">This is the fouth pop up selected</span>
</div>
&#13;
您可能还想查看隐藏已显示的弹出窗口。