[英]how to change color of <li> elements on hover using javascript or jquery?
我想在悬停时更改<li>
元素的颜色。 像中,当我在苹果或香蕉它shold悬停以下示例代码示出了颜色棕色到相应的<li>
元素一整套<li>
元素,并且当我悬停梨或图<li>
元素它应该显示黄色相应的<li>
元素上的颜色。
HTML:
<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>
CSS:
#tree > ul > li:hover {
background:brown;
}
#tree > ul > li:hover > ul >li{
background:white;
}
#tree > ul > li > ul > li:hover {
background:yellow;
}
JS:
$(document).ready(function () {
$("#tree > ul > li > ul > li").hover(
function() {
$("#tree > ul > li").css("background","white");
$("#tree > ul > li > ul > li").css("background","yellow");
},
function() {
$("#tree > ul > li > ul > li").css("background","white");
});
$("#tree > ul > li").hover(
function() {
$("#tree > ul > li > ul > li").css("background","white");
$("#tree > ul > li").css("background","brown");
},
function() {
$("#tree > ul > li").css("background","white");
});
});
这是相当简化和分离的:
.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>
好吧,如果您将删除自己的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");
}
});
演示:
我不确定您想要实现什么,但是我认为您不需要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
元素。
我不得不编辑您的HTML , CSS以及jQuery
li
并为其指定了list-style: none; background-color: #fff;
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"); }); });
#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;
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.