所以我有一个有三列的表格,在最后一列中,我有一个单词,当点击它时,它会在单词的正上方显示一个弹出窗口。 我的问题是弹出窗口总是显示在同一个位置,就在第一行,第三列的单词上方。 因此,如果我在第5行点击单词,弹出窗口就会出现,就像在第1行点击了单词一样。 我想让它直接显示在单词上方的相应行上,它被点击了。
null
function openPopup() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}
#table {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 1000px;
margin: 8px auto 0px;
}
#table td,
#table th {
border: 1px solid #ddd;
padding: 8px;
}
#table tr:nth-child(even) {
background-color: #f2f2f2;
}
#table th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: gray;
color: white;
}
.popup {
position: relative;
display: inline-block;
cursor: pointer;
}
.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;
animation: fadeIn 1s
}
@-webkit-keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
<table width='100%' id='table'>
<tr>
<th><b>Coluna1:</b></th>
<th><b>Coluna2:</b></th>
<th><b>Coluna3:</b></th>
</tr>
<tr>
<td>Word1</td>
<td>Text1</td>
<td>
<center>
<div class='popup' onclick='openPopup()'>Show1
<span class='popuptext' id='myPopup'>Popup text...</span>
</div>
</center>
</td>
</tr>
<tr>
<td>Word2</td>
<td>Text2</td>
<td>
<center>
<div class='popup' onclick='openPopup()'>Show2
<span class='popuptext' id='myPopup'>Popup text...</span>
</div>
</center>
</td>
</tr>
<tr>
<td>Word3</td>
<td>Text3</td>
<td>
<center>
<div class='popup' onclick='openPopup()'>Show3
<span class='popuptext' id='myPopup'>Popup text...</span>
</div>
</center>
</td>
</tr>
</table>
null
如何更改代码以实现这一点?
老实说,这是我在StackOverflow上的第一个答案,所以请耐心等待,哈哈。
您可能希望尝试QuerySelectorAll(“#MyPopup”)
,因为与GetElementById(“MyPopup”)
相比,这将选择所有span元素。
如果这不起作用,我会尝试给他们一个唯一的id,并从那里工作,但这将需要一些更多的工作,当然。
祝你好运!
这是因为您使用相同的标识符,所以javascript访问它找到的第一个标识符并添加类。
我想到的解决方案是为每个元素指定唯一的id,并将其传递给javascript方法。
HTML
<td>
<center>
<div class='popup' onclick='openPopup(this)'>Show1
<!-- We pass "this" to openPopup -->
<span class='popuptext' id='myPopup1'>Popup text...</span>
</div>
</center>
</td>
JS
function openPopup(element) {
// We receive the item and access its id
let myChildElementId = element.childNodes[1].id;
let popup = document.getElementById(myChildElementId);
popup.classList.toggle("show");
}
现在,每次启动函数时,都会传递元素及其唯一的ID。
下面是完整的示例。