当我将父元素悬停时,他的孩子出现了。当我单击父元素时,他的孩子也会出现,而当我再次单击它时,他的孩子也会消失。但是然后(在单击父元素以消失的孩子之后)当我将父元素悬停时,他的孩子没有出现。为什么?
var parent = document.querySelector('nav > ul > li');
var children = document.querySelector('nav > ul > li > ul');
parent.addEventListener('click', function () {
if (children.style.display == 'block') {
children.style.display = 'none';
} else {
children.style.display = 'block';
}
});
nav > ul > li > ul {
display: none;
}
nav > ul > li:hover ul {
display: block;
}
li {
width: max-content;
}
ul {
padding: 0px;
}
<body>
<nav>
<ul>
<li><a href="#">Parent</a>
<ul>
<li><a href="#">child</a></li>
<li><a href="#">child</a></li>
</ul>
</li>
</ul>
</nav>
</body>
谢谢。
答案 0 :(得分:4)
单击父级时,切换班级比较容易。
var parent = document.querySelector('nav > ul > li');
var children = document.querySelector('nav > ul > li > ul');
parent.addEventListener('click', function() {
children.classList.toggle("showIt");
});
nav>ul>li>ul {
display: none;
}
nav>ul>li:hover ul {
display: block;
}
li {
width: max-content;
}
ul {
padding: 0px;
}
.showIt {
display: block;
}
<body>
<nav>
<ul>
<li><a href="#">Parent</a>
<ul>
<li><a href="#">child</a></li>
<li><a href="#">child</a></li>
</ul>
</li>
</ul>
</nav>
</body>
答案 1 :(得分:2)
您可以通过将children.style.display
设置为空字符串来轻松避免这种情况,而不必在隐藏孩子时为其分配none
。
编辑:
需要更正:不是将未定义的空字符串分配给children.style.display
才能删除替代项(请参见斜体标记的文本-我必须对其进行更正)。
代码段应如下所示:
var parent = document.querySelector('nav > ul > li');
var children = document.querySelector('nav > ul > li > ul');
parent.addEventListener('click', function () {
alert(children.style.display);
if (children.style.display == 'block') {
children.style.display = '';
} else {
children.style.display = 'block';
}
}, true);
答案 2 :(得分:0)
使用基本的编程语言
$('#target').on('click mouseover', function () {
// Do something for both
});