[英]Change Text Colour When Hovering Over Another Element on the Same Level
I am trying to change the text colour of .foo
when the user hovers over .bar
and I am unsure how to do this with only CSS. 当用户将鼠标悬停在.bar
,我试图更改.foo
的文本颜色,我不确定如何仅使用CSS来执行此操作。 I have tried using the CSS preceding element selector ~
but that did not work. 我试过使用CSS前面的元素选择器~
但是没有用。
http://jsfiddle.net/847E2/ http://jsfiddle.net/847E2/
<div>
<p class="foo">Foo</p>
<ul class="bar"><li>Bar<li></ul>
</div>
.bar:hover~.foo {
color: red;
}
EDIT - My requirements have changed. 编辑-我的要求已更改。 I updated my HTML structure to make the .bar
a <ul>
我更新了HTML结构,使.bar
成为<ul>
The sibling selector ~
doesn't select elements preceding it, just elements succeeding it. 同级选择器~
不会选择其前面的元素,而只会选择其后的元素。 Thus, when hovering over the element .bar
, the element .foo
cannot be selected, as it is preceding .bar
. 因此,将.bar
悬停在元素.bar
,无法选择元素.foo
,因为它位于.bar
之前。
You could do something like this instead: 您可以改为执行以下操作:
div:hover :not(:hover) {
color: red;
}
Basically, this is setting the color of the child elements to color:red
when hovering over the parent, div
. 基本上,这是将鼠标悬停在父元素div
时,将子元素的颜色设置为color:red
。 However, it will not be applied on :hover
of the element you are on. 但是,它不会应用于您所在元素的:hover
。 This makes it seem as though the color is changing when you hover over the sibling element. 当您将鼠标悬停在同级元素上时,这似乎使颜色发生变化。
The + selector is an adjacent sibling combinator selector allows you to select an element that is directly after another specific element. +选择器是相邻的同级组合器选择器,可让您选择紧接在另一个特定元素之后的元素。
It doesn't matter if you use any element if have .bar class name. 是否具有.bar类名称都可以使用任何元素。
NOTE: There is no "previous sibling" selector, that's why i change the elements order in the DOM. 注意:没有“上一个兄弟”选择器,这就是为什么我更改DOM中的元素顺序的原因。
.bar:hover + .foo {
color: red;
}
Demo http://jsfiddle.net/847E2/11/ 演示http://jsfiddle.net/847E2/11/
Also can see: http://css-tricks.com/child-and-sibling-selectors/ 也可以查看: http : //css-tricks.com/child-and-sibling-selectors/
Is there a "previous sibling" CSS selector? 是否有一个“先前的兄弟” CSS选择器?
Here's a way to do it with CSS (no CSS3 needed): 这是使用CSS的一种方法(不需要CSS3):
div:hover p{
color: red;
}
.foo:hover{
color: black;
}
div:hover p.bar{
color: black;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.