html 显示属性无法使用 javascript 更改
2020-10-08
56
该脚本适用于#Mylinks,但对于#myLinks2。
#mylinks2的唯一功能是图片更改
样式
126827864
1个回答
委托并使用类
我移动了链接,以便它们在 div 打开时不会移动
document.getElementById("container").addEventListener("click", function(e) {
let tgt = e.target;
const parent = tgt.closest("a");
if (tgt.tagName === "IMG" && parent && parent.classList.contains("toggle")) tgt = parent;
if (tgt.classList.contains("toggle")) {
e.preventDefault(); // stop link
tgt.classList.toggle("open");
const open = tgt.classList.contains("open")
tgt.querySelector("img").src = open ? "https://img.icons8.com/flat_round/2x/minus.png" : "https://img.icons8.com/flat_round/2x/plus.png";
document.getElementById(tgt.dataset.id).classList.toggle("hide", !open);
}
})
.hide {
display: none;
}
.toggle {
background-color: #ccc;
color: white;
}
<div id="container">
<a class="toggle" href="#" data-id="myLinks">
<img src="https://img.icons8.com/flat_round/2x/plus.png" height="42" width="42"> travel to
</a>
<a class="toggle" href="#" data-id="myLinks2">
<img src="https://img.icons8.com/flat_round/2x/plus.png" height="42" width="42"> tour type
</a>
<div id="myLinks" class="hide">
<a href="athen.php">----Athens</a>
</div>
<div id="myLinks2" class="hide">
<a href="city.php">----Per city</a>
</div>
</div>
mplungjan
2020-10-08