在此代码中:
<div id="Container">
<span class='first'>First</span>
<span class='second'>Second</span>
<span class='third'>Third</span>
</div>
我希望在:hover
时更改颜色。
.first:hover
)THEN .first { color: red; }
.second:hover
)THEN .first, .second { color: red; }
.third:hover
)THEN .first, .second, .third { color: red; }
没有JS,这可能吗?我可以接受CSS Hacks:)
可能的答案:
更难的版本:
<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>
.first:hover
)THEN .first { color: pink; }
.second:hover
)THEN .first, .second { color: pink; }
.third:hover
)THEN .first, .second, .third { color: pink; }
答案:
答案 0 :(得分:7)
在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 {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}
答案 1 :(得分:1)
这就是我认为可以做的事情,你想要实现整洁的目标
@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);
}
希望它有所帮助!
答案 2 :(得分:1)
我找到了@each
in SASS基于panther's answer的方法:
$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 */
&#13;
<div id="FirstSecondThird-Container">
<span class='first'>First</span>
<span class='second'>Second</span>
<span class='third'>Third</span>
</div>
&#13;
其中有与panther's fiddle类似的CSS规则。
很好的挑战 123qwe :)