如果我的隱藏元素(下拉列表)在單擊父元素時(shí)打開,在這種情況下,我如何通過單擊另一個(gè)父元素來關(guān)閉它們?這是我在js中的代碼
function toggleElement(elementId) {
var element = document.querySelector(elementId);
element.style.display = element.style.display === "none" ? "block" : "none";
}
document.addEventListener("DOMContentLoaded", function() {
var buttons = document.getElementsByClassName("ContainerForMenu");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function() {
var target = this.getAttribute("data-target");
toggleElement(target);
});
}
});
作為一個(gè)解決方案,我嘗試了這個(gè)選項(xiàng),但它不起作用
function toggleElement(elementId) {
var elements = document.querySelectorAll('.child-element');
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = "none";
}
var element = document.querySelector(elementId);
element.style.display = "block";
}
document.addEventListener("DOMContentLoaded", function() {
var buttons = document.getElementsByClassName("ContainerForMenu");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function() {
var target = this.getAttribute("data-target");
toggleElement(target);
});
}
});
跟隨我的代碼您可以使用toggle基于按鈕單擊來切換元素的可見性...
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>