如何在html中悬停时更改li elment的颜色?

时间:2015-07-24 07:39:10

标签: javascript jquery html css

我想在悬停时更改<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;
}

https://jsfiddle.net/1v57nwg8/

任何使用css,javascript或jquery赞助的帮助。

3 个答案:

答案 0 :(得分:2)

在LI的文本内容周围放置一个SPAN或其他内容:

HTML:

<div id="tree">
    <ul>
        <li><span>apple</span></li>
        <li><span>banana</span></li>
        <li><span>mango</span>
            <ul>
                <li><span>date</span></li>
                <li><span>pear</span></li>
                <li><span>fig</span></li>
            </ul>
        </li>
    </ul>
</div>

CSS:

#tree > ul > li:hover > span {
   background:brown;
}
#tree > ul > li > ul > li:hover > span {
   background:yellow;
}

答案 1 :(得分:0)

如果我正确猜测您的问题,您需要为孩子ul添加规则,以便 背景不会从其父级继承其颜色li

#tree > ul > li:hover > ul {
   background:white;
}

直播示例

&#13;
&#13;
#tree > ul > li:hover {
   background:brown;
}
#tree > ul > li:hover > ul >li{
   background:white;
}
#tree > ul > li > ul > li:hover {
   background:yellow;
}
/* This is the new rule: */
#tree > ul > li:hover > ul {
   background:white;
}
&#13;
<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>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

试试这个:

&#13;
&#13;
#tree > ul > li:hover > div {
   background:brown;
}
#tree > ul > li > ul > li:hover {
   background:yellow;
}
&#13;
<div id="tree">
<ul>
    <li><div>apple</div></li>
    <li><div>banana</div></li>
    <li><div>mango</div>
        <ul>
            <li>date</li>
            <li>pear</li>
            <li>fig</li>
        </ul>
    </li>
</ul>
&#13;
&#13;
&#13;