[英]Keep :hover effect on parent, when mouse is over child
I have a new problem with my menu. 我的菜单有新问题。
I want to keep the parent hover effect active when mouse is over child. 我想在鼠标悬停在孩子上方时保持父悬停效果有效。
I know I could maybe use jQuery? 我知道我可以使用jQuery吗? but I really wanna keep it in CSS if possible.
但我真的想尽可能地将其保留在CSS中。
And without having to give all elements unique id's... 而且不必给所有元素唯一的ID ...
http://forevertan.dk/_temp/eventfest/3/test3.htm http://forevertan.dk/_temp/eventfest/3/test3.htm
Put the :hover selector on the li
element rather than the anchor 将:hover选择器放在
li
元素而不是锚点上
#navMain li:hover > a{
background-color: black;
}
If you want to use a CSS only way, what I highly recommend to you, you would have to change your markup a little bit. 如果您只想使用CSS,我强烈建议您使用,那么您就必须对标记做些改动。 When you check for
:hover
on a
's parent (the li
) a
will still be on :hover
when you go down the submenu. 当您检查
:hover
于a
的父(中li
) a
仍然将是:hover
当你去了子菜单。 Basically we're doing this: 基本上,我们正在这样做:
ul#nav li > a {
/* all the normal state styling here */
}
ul#nav li:hover > a {
/* hover state styling here */
}
We will expand the a
to the dimensions of the li
. 我们将扩大
a
到的尺寸li
。 So the li
seems to behave like the a
. 所以
li
似乎表现得像a
。 The only difference is, that the li
is the parent of the a
and the submenu ul
. 唯一的区别是,
li
是a
和子菜单ul
的父级。
HTML stays the same: HTML保持不变:
<ul id="nav">
<li>
<a href="#test">Test</a>
<ul>
<li>
<a href="#test/sub">Sub</a>
</li>
</ul>
</li>
<li>
<a href="#test">Test</a>
<ul>
<li>
<a href="#test/sub">Sub</a>
</li>
</ul>
</li>
</ul>
CSS changes: CSS更改:
ul#nav > li {
padding: 0;
margin: 0;
float: left;
position: relative;
}
ul#nav li > a {
height: 30px;
min-width: 80px;
padding: 0;
margin: 0;
border-right: 1px solid #CCC;
border-left: 1px solid #CCC;
display: block;
background: #000;
color: #FFF;
text-align: center;
line-height: 30px;
white-space: nowrap;
}
ul#nav li:hover > a {
background: #FFF;
color: #000;
}
ul#nav > li ul {
display: none;
position: absolute;
}
ul#nav > li:hover ul {
display: block;
}
ul#nav > li ul li {
display: block;
}.
You cannot effect parent items with CSS; 您不能使用CSS来影响父项。 you need to use JavaScript.
您需要使用JavaScript。 If you don't like IDs you can use jQuery's relative selectors
.parent()
, .next()
etc. 如果您不喜欢ID,则可以使用jQuery的相对选择器
.parent()
.next()
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.