我想在悬停时更改<li>
元素的颜色。就像在下面的示例代码中,当我将鼠标悬停在苹果或香蕉上时,它会显示棕色到相应的<li>
元素到整个<li>
元素的颜色,当我将鼠标悬停在梨或图{{1}上时} element它应该在相应的<li>
元素上显示黄色。
HTML:
<li>
CSS:
<div id="tree">
<ul>
<li>apple</li>
<li>banana</li>
<li>mango
<ul>
<li>date</li>
<li>pear</li>
<li>fig</li>
</ul>
</li>
</ul>
JS:
#tree > ul > li:hover {
background:brown;
}
#tree > ul > li:hover > ul >li{
background:white;
}
#tree > ul > li > ul > li:hover {
background:yellow;
}
});
答案 0 :(得分:1)
这非常简化并且解耦:
.hover-brown:hover{
background-color: brown;
}
.hover-yellow:hover{
background-color: yellow;
}
.no-list-style{
list-style: none;
}
<div id="tree">
<ul>
<li class="hover-brown">apple</li>
<li class="hover-brown">banana</li>
<li class="hover-brown">mango</li>
<li class="no-list-style">
<ul>
<li class="hover-yellow">date</li>
<li class="hover-yellow">pear</li>
<li class="hover-yellow">fig</li>
</ul>
</li>
</ul>
</div>
答案 1 :(得分:0)
好吧,如果你将删除你的jquery代码,它会因为css而发挥作用。
但是如果你仍然想通过jQuery使用,那么
使用$(this),如下所示: -
$(document).ready(function () {
$("#tree > ul > li > ul > li").hover(
function() {
$(this).css("background","yellow");
}
$("#tree > ul > li").hover(
function() {
$(this).css("background","brown");
}
});
演示: -
答案 2 :(得分:0)
我不确定你想要达到什么目标,但我认为你不需要JS。
看看演示: https://jsfiddle.net/mattydsw/1v57nwg8/4/
下面的CSS:
#tree > ul > li:hover span {
background:brown;
}
#tree > ul > li > ul > li:hover {
background:yellow;
}
我还在html标记中添加了span
个元素。
答案 3 :(得分:0)
我必须修改 HTML , CSS 以及 jQuery
li
,并为其提供了list-style: none; background-color: #fff;
this
this
将选择当前悬停元素,而不是选择所有元素
$(document).ready(function () {
$("#tree > ul > li > ul > li").hover(
function() {
$(this).css("background","yellow");
},
function() {
$(this).css("background","white");
});
$("#tree > ul > li").hover(
function() {
$(this).css("background","brown");
},
function() {
$(this).css("background","white");
});
});
&#13;
#tree > ul > li:hover {
background:brown;
}
#tree > ul > li:hover > ul >li{
background:white;
}
#tree > ul > li > ul > li:hover {
background:yellow;
}
#tree>ul>li:last-child {
list-style: none;
background-color: #fff;
}
#tree > ul > li > ul {
background-color: white;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tree">
<ul>
<li>apple</li>
<li>banana</li>
<li>mango</li>
<li>
<ul>
<li>date</li>
<li>pear</li>
<li>fig</li>
</ul>
</li>
</ul>
</div>
&#13;