嵌套 Div 悬停问题
我有3个这样的html div:
<div id="MainDiv">
<div id="nesteddiv1"></div>
<div id="nesteddiv2"></div>
</div>
我希望当我将鼠标悬停在 MainDiv 或nestedDiv1 上时,我为 MainDiv 设置颜色 1 ,为nesteddiv2 设置颜色 2 ,然后当我将鼠标悬停在nesteddiv2 上时,我更改nesteddiv2 和 MainDiv 的背景颜色。
我更喜欢用 CSS 来做,我知道 javascript 的方式。
谢谢 马兹达克
I have 3 html div like this:
<div id="MainDiv">
<div id="nesteddiv1"></div>
<div id="nesteddiv2"></div>
</div>
I want when I hover on MainDiv or nestedDiv1 , I set color 1 for MainDiv and color 2 for nesteddiv2 , then when I hover on nesteddiv2 I change the backgroundcolor of nesteddiv2 and MainDiv.
I prefer to do it with CSS, I know the javascript way.
Thanks
Mazdak
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 CSS 中,无法使用包含其后代之一的选择器来定位元素。因此,虽然前半部分实现起来微不足道,但后半部分却是不可能实现的。
如果这很重要,请使用 JavaScript。
There is no way, in CSS, to target an element using a selector that includes one of its descendents. So while the first half is trivial to achieve, the second half is impossible.
Use JavaScript if it matters that much.
对于给定的 HTML,您可以使用以下 CSS
注意:这在 IE 中不起作用,因为它仅支持将鼠标悬停在标签上。
For given HTML you can do with following CSS
Note: This will not work in IE as it supports hover only on a tag.
没有办法从另一个元素中选择一个元素,这是不可能的。
但是您可以使用 jQuery 来做到这一点,如下所示:
我在这里为您制作了一个示例。
There is no way to select an element from another, it's just not possible.
But you can do this with jQuery like this:
I have made an example for you here.
仅使用 CSS 实现此目的的唯一方法是在悬停发生时使用额外的 div 来覆盖 maindiv。并且它不适用于 IE < v9,因为它需要 z-index
这将是标记
CSS 将非常棘手。
(免责声明:这尚未经过测试 - 可能您需要更多规则)
z-index 将使 maindiv 始终位于其他 div 后面,而嵌套 div 1 和 2 始终位于顶部。 extradiv 将位于它们之间,“覆盖”maindiv,但仅当 Nesteddiv2 悬停时才有效。
此方法的一个缺点是 extradiv 会一直可见,直到您停止悬停它,而不仅仅是nesteddiv2。
The only way of doing that with CSS only is using an extra div to cover maindiv when the hover happens. And it would not work on IE < v9, since it would need z-index
This would be the markup
The CSS would be very tricky.
(disclaimer: this hasn't been tested - probably you would need more rules)
z-index would make maindiv stay allways behind the others, while nested divs 1 and 2 always stay on top. extradiv would be between them, 'covering' maindiv, but only when nesteddiv2 is hovered.
A drawback of this method would be that extradiv would be visible until you stopped hovering it, not just nesteddiv2.