简短的问题:为什么当我悬停时background-color
of.b
不会改变?.a
?
CSS
.a {
color: red;
}
.b {
color: orange;
}
.a:hover .b {
background-color: blue;
}
HTML
<div id="wrap">
<div class="a">AAAA</div>
<div class ="b">BBBB</div>
</div>
简短的问题:为什么当我悬停时background-color
of.b
不会改变?.a
?
CSS
.a {
color: red;
}
.b {
color: orange;
}
.a:hover .b {
background-color: blue;
}
HTML
<div id="wrap">
<div class="a">AAAA</div>
<div class ="b">BBBB</div>
</div>
你需要有.a:hover + .b
而不是.a:hover .b
.a:hover .b
将适用于像这样的结构
<div class="a">AAAA
<div class ="b">BBBB</div>
</div>
如果在某些时候你需要在 .a 和 .b 之间有一些元素,那么你需要使用.a:hover ~ .b
,它适用于所有后继的兄弟姐妹.a
,而不仅仅是下一个。
你不能做类似的事情a:hover + b
吗?见http://meyerweb.com/eric/articles/webrev/200007a.html
您可以使用 + 选择器
.a:hover + .b {
background-color: blue;
}
为兄弟元素应用 css,或
.a:hover > .b {
background-color: blue;
}
对于嵌套类。
因为 .b 不是 .a 的子级,所以选择器没有找到任何东西。使用 javascript 做你想做的事。
你可以做两件事。
要么更改您的 HTML 以使其.b
成为.a
<div id="wrap">
<div class="a">AAAA
<div class ="b">BBBB</div>
</div>
</div>
或者
更改您的 css 以使用相邻的选择器
.a:hover + .b {
background-color: blue;
}
不需要 js http://jsfiddle.net/2NEgt/3/
当事件发生在不同的元素上时,您不应该更改兄弟的样式。它脱离了 CSS 的上下文。
使用 JavaScript 来实现这一点,例如:
var wrap = document.getElementById("wrap");
var aDiv = wrap.getElementsByClassName("a")[0];
var bDiv = wrap.getElementsByClassName("b")[0];
aDiv.onmouseover = function() {
bDiv.style.backgroundColor = "red";
};
aDiv.onmouseout = function() {
bDiv.style.backgroundColor = "white";
};
试着理解这个例子:
html代码
<p>Hover over 1 and 3 gets styled.</p>
<div id="one" class="box">1</div>
<div id="two" class="box">2</div>
<div id="three" class="box">3</div>
<!--css-->
#one:hover ~ #three{
background-color: black;
color: white;
}
.box {
cursor: pointer;
display: inline-block;
height: 30px;
line-height: 30px;
margin: 5px;
outline: 1px solid black;
text-align: center;
width: 30px;
}
当您将鼠标悬停在框 1 上时,框 3 将变为黑色
Jquery 是一个很好且简单的解决方案:
html:
<div class="a">AAA</div>
<div class="b">BBB</div>
脚本: 如果需要,可以将此脚本放入您的 html 中。就这样。
<script>
$(".a").mouseover(function(){
$(".b").css("color", "blue");
});
$(".a").mouseleave(function(){
$(".b").css("color", "red");
});
</script>