我正在一个网站上工作,当我将鼠标悬停在该子栏或该导航栏后代的链接上时,我想要更改整个导航栏的颜色。
.containernav {
margin: 0;
padding: 0;
background-color: grey;
}
/*home*/
#home {
color: white;
}
#home:hover {
background-color: white;
}
/*playstation*/
#playstation {
color: white;
}
#playstation:hover{
background-color: blue;
}
/*xbox*/
#xbox {
color: white;
}
#xbox:hover{
background-color: green;
}
/*pcgaming*/
#pcgaming {
color: white;
}
#pcgaming:hover {
background-color: #FFBA00;
}
nav > ul {
list-style: none;
}
nav > ul > li > a {
text-decoration: none;
}
<div class="containernav" id="a">
<nav>
<ul>
<li><a id="home" href="index.html">Home</a></li>
<li><a id="playstation" href="playstation.html">Playstation</a></li>
<li><a id="xbox" href="xbox.html">XBox</a></li>
<li><a id="pcgaming" href="pcgaming.html">PC-Gaming</a></li>
</ul>
</nav>
</div>
我当前的实现只会更改自身链接的颜色,而不会更改css样式类 containernav 的容器。需要更改什么才能更改该容器的背景颜色?
答案 0 :(得分:1)
使用css无法实现。关于这个问题有几个主题 - 其中一些要求:父选择器,其中一些人认为这将是一个巨大的性能问题。 但是,如果这是一个选项,您可以使用javascript执行此操作。 以下是Jquery的一个简单示例:
$("#child").hover(function(){
$(this).parent().css("bakground,"red");
//This should be ajusted according your needs
// Can be achieved with data attribute, custom class etc..
});
答案 1 :(得分:0)
JQuery的
$( document ).ready(function() {
$("#home").hover(
function() {
$(".containernav").addClass("white-bg");
}, function() {
$(".containernav").removeClass("white-bg");
}
);
$("#playstation").hover(
function() {
$(".containernav").addClass("blue-bg");
}, function() {
$(".containernav").removeClass("blue-bg");
}
);
// and so on..
});
CSS
.white-bg {background-color:white;}
.blue-bg {background-color:blue;}
// and so on