在此代码中:
<div id="Container">
<span class='first'>First</span>
<span class='second'>Second</span>
<span class='third'>Third</span>
</div>
我想改变颜色,当:hover
.
- if (
.first:hover
) then.first { color: red; }
- if (
.second:hover
) then.first, .second { color: red; }
- if (
.third:hover
) then.first, .second, .third { color: red; }
如果没有JS,这是可能的吗?我可以接受CSS hack:)
可能的答案:
- @panther的回答
更难的版本:
<div id="Container">
<span class='first' style='color: red'>First</span>
<span class='second' style='color: green'>Second</span>
<span class='third' style='color: blue'>Third</span>
</div>
- if (
.first:hover
) then.first { color: pink; }
- if (
.second:hover
) then.first, .second { color: pink; }
- if (
.third:hover
) then.first, .second, .third { color: pink; }
答案:
- @Armfoot的回答似乎很好:)
在CSS中没有先前的兄弟选择器,但是…有时可以使用已知的选择器。有时候。
<style>
span {color: #000; display: block;}
div:hover span {color: #f00;}
span:hover ~ span {color: #000}
</style>
<div id="FirstSecondThird-Container">
<span class='first'>First</span>
<span class='second'>Second</span>
<span class='third'>Third</span>
</div>
https://jsfiddle.net/45zLdcvr/它适用于block
span
s(当然是浮动的)。span
s有默认的display: inline
,当你将div
悬停在跨度之间的空间时,它会闪烁。
:
当每个span都有自己的颜色时,您更新了问题,那么它可以是:
span {color: red}
.second {color: green}
.third {color: blue}
span {display: block;}
div:hover span {color: pink;}
span:hover ~ .second {color: green}
span:hover ~ .third {color: blue}
https://jsfiddle.net/45zLdcvr/1/根据panther的回答,我想出了一个在SASS中使用@each
的方法:
$containerID: FirstSecondThird-Container;
##{$containerID}:hover span {color:pink}
@each $spanclass, $spancolor in (first, red), (second, green), (third, blue) {
##{$containerID} span:hover ~ .#{$spanclass}, .#{$spanclass} {
color: #{$spancolor};
}
}
它有点短,但这是结果(生成的CSS):
#FirstSecondThird-Container:hover span {
color: pink;
}
#FirstSecondThird-Container span:hover ~ .first, .first {
color: red;
}
#FirstSecondThird-Container span:hover ~ .second, .second {
color: green;
}
#FirstSecondThird-Container span:hover ~ .third, .third {
color: blue;
}
span {display: block;} /* this line was not generated, it's just to place them vertically */
<div id="FirstSecondThird-Container">
<span class='first'>First</span>
<span class='second'>Second</span>
<span class='third'>Third</span>
</div>
与panther's fiddle的CSS规则相似。
123年<<p>好挑战strong> qwe :)我认为这就是你想要达到的目标
@mixin color_on_hover($class){
@if $class==first {span:nth-of-type(1){color:red;}}
@else if $class==second {span:nth-of-type(1), span:nth-of-type(2){color:red;}}
@else if $class==third {span:nth-of-type(1), span:nth-of-type(2), span:nth-of-type(3){color:red;}}
}
span.first:hover{
@include color_on_hover(first);
}
span.second:hover{
@include color_on_hover(second);
}
span.third:hover{
@include color_on_hover(third);
}
希望有帮助!