[英]How to add :hover and click event to element same time?
When I hover parent element his child is appear. 当我悬停父元素时,他的孩子就会出现。 When I click parent element his child also appear and when I click it again his child disappear.
当我单击父元素时,他的孩子也会出现,而当我再次单击它时,他的孩子也会消失。 But then(after clicking parent element for disappearing child) when I hover parent element his child is not appearing.
但是然后(在单击父元素以消失的孩子之后)当我将父元素悬停时,他的孩子没有出现。 Why?
为什么?
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>
Thanks. 谢谢。
It is easier to toggle a class when the parent is clicked. 单击父级时,切换班级比较容易。
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>
You can easily avoid this by setting children.style.display
to the empty string instead of assigning none
to it when you want to hide the children. 您可以通过将
children.style.display
设置为空字符串来轻松避免这种情况,而不是在要隐藏子项时none
给它分配none
内容。
EDIT: 编辑:
Need a correction: Instead of undefined the empty string needs to be assigned to children.style.display
to drop the override (see the text marked in italics - I had to correct that). 需要更正:无需将未定义的空字符串分配给
children.style.display
即可删除覆盖(请参见斜体标记的文本-我必须对其进行更正)。
The code snippet should look like this: 该代码段应如下所示:
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);
Use basic programming composition 使用基本编程组成
$('#target').on('click mouseover', function () {
// Do something for both
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.