问题
I Want to change the background of a Div when Hovering over another Div and i tried
HTML5 part:
<nav>
<div id="nav1"></div>
<a href="#"><div id="nav2"></div></a>
<a href="#"><div id="nav3"></div></a>
<a href="#"><div id="nav4"></div></a>
<a href="#"><div id="nav5"></div></a>
<a href="#"><div id="nav6"></div></a>
<div id="nav7"></div>
</nav>
<article>
<div id="nav8"></div>
</article>
And the CSS i tried is
#nav2
{
float:left;
height:429px;
width:34px;
background:url(images/nav_02.gif) no-repeat;
}
#nav2:hover #nav8
{
float:left;
height:429px;
width:445px;
background:url(images/nav_08-nav_02_over.jpg) no-repeat;
}
But it is not working ... I need to do it with css only no javascript ..
回答1:
The way CSS selectors works is Parent > Descendant
When you do
#nav2:hover #nav8
It means that #nav8 is a descendant of #nav2, which is not the case in your markup, so the rule does not apply
You have to use javascript to do what you're after.
回答2:
It's impossibru. You can change the background of the div itself, and any child divs, when you are hovering it, but with a sibling/parent sibling/completely unrelated element - no way.
You could, however, do it in jQuery.
Example:
$("#nav2").mouseover(function() {
$("#nav8").addClass("someClassName");
});
$("#nav2").mouseout(function() {
$("#nav8").removeClass("someClassName");
});
And then hook up that background-image to #nav8.someClassName.
回答3:
Use this Jquery code:
<script type="text/javascript">
$(document).ready(function(){
$("#nav2").hover(function(){
$("#nav8").css("background-image","url(images/nav_08-nav_02_over.jpg)");
},function(){
$("#nav8").css("background-image","");
});
});
</script>
回答4:
There is no way you can add effects on same level tags in CSS3. On hover of a parent tag only child tags can have different CSS.
回答5:
it's impossible unless your div
are siblings, so you can achieve the effect using
+
adjacent siblings selectors (css2) or ~
general siblings combinator (css3)
e.g. if your markup is structured in this way
<div id="nav1"></div>
<div id="nav2"></div>
...
<div id="nav9"></div>
you can apply some style to nav2
hovering nav1
with
#nav1:hover + #nav2 { ... }
because nav2 is an immediate (adjacent) sibling of nav1 (in this case +
or ~
would have the same effect), or you can do the same on nav9
hovering nav1
with
#nav1:hover ~ #nav9 { ... }
(here you can use only the ~
selector.)
Note also that these selectors are available on all modern browser including Internet Explorer 7+, see http://html5please.us/#gtie6
来源:https://stackoverflow.com/questions/9001229/want-to-change-the-background-of-an-div-on-hovering-another-div-in-css3