是否可以根据类名在没有 Javascript 的情况下更改悬停时的多个元素外观?
我在 div
s 中有一个 div
s 结构,类似于:
<div class='a'>你好</div><div class='a'>堆栈</div><div>溢出</div></div><div>你</div><div class='b'>是</div><div class='b'>最好的</div></div><div>有</div><div class='b'>一个不错的</div><div>日!!</div></div></div>
我希望所有具有类 a
的 div
在其中一个被鼠标悬停时更改背景颜色.对于所有具有类 b
的 div
都相同:当悬停具有类 b
的 div
之一时,所有div
s with class b
应该改变背景颜色.
是否有可能实现此行为无需 Javascript?
如果答案是否定的:
如果知道所有具有类 a
的 div
都是连续的 div
是否可能在同一级别(即兄弟姐妹)?
如果需要,我还可以将其他类添加到 div
s.
在没有容器 <div>
s 的更简单的情况下,你可以让它工作一半":
<div class='a'>你好</div><div class='a'>堆栈</div><div>溢出</div><div class='b'>是</div><div class='b'>最好的</div><div>有</div><div class='b'>一个不错的</div><div>日!!</div></div>
然后你可以使用 通用兄弟组合器, 不幸的是,它仅适用于左侧描述的元素之后的元素.因此,例如,如果您将鼠标悬停在包含The Best"的 <div>
上,那么只有那个和a nice"的 <div>
会发生变化背景:
div.b:hover, div.b:hover ~ div.b {背景颜色:#CCCCCC;}
不过,我无法想出一种仅通过 CSS 来完全处理您的场景的方法.我倾向于其他人所说的现在不可能(即使在简化的情况下).
I have a structure of div
s inside div
s, something like:
<div>
<div>
<div class='a'>Hello</div>
<div class='a'>Stack</div>
<div>Overflow</div>
</div>
<div>
<div>You</div>
<div class='b'>Are</div>
<div class='b'>The Best</div>
</div>
<div>
<div>Have</div>
<div class='b'>a nice</div>
<div>Day !!</div>
</div>
</div>
I would like all div
s with class a
to change the background color when one of them is hovered by mouse. The same for all div
s with class b
: when one of div
s with class b
is hovered, all div
s with class b
should change the background color.
Is that possible to implement this behavior without Javascript ?
If the answer is no:
Is that possible if known that all div
s with class a
are consecutive div
s in the same level (i.e. siblings) ?
I can add also other classes to div
s, if needed.
You can get it "half working" in the simpler case where there are no container <div>
s:
<div>
<div class='a'>Hello</div>
<div class='a'>Stack</div>
<div>Overflow</div>
<div class='b'>Are</div>
<div class='b'>The Best</div>
<div>Have</div>
<div class='b'>a nice</div>
<div>Day !!</div>
</div>
Then you could use the general sibling combinator, with the unfortunate caveat that it only works for elements that come after the element described on the left-hand side. So, for example, if you hovered over the <div>
containing "The Best", only that and the "a nice" <div>
would have a changed background:
div.b:hover, div.b:hover ~ div.b {
background-color:#CCCCCC;
}
I wasn't able to come up with a way that would fully take care of your scenario through CSS alone, though. I'm leaning towards what the others have said about it not being possible (even in the simplified case) right now.
相关文章