开发者

Nested Li Elements Hover Alternate Background Color

开发者 https://www.devze.com 2023-02-12 07:27 出处:网络
Here\'s a quick overview of my problem.I\'ve got a list with initial background color 1 like this: <ul>

Here's a quick overview of my problem. I've got a list with initial background color 1 like this:

<ul>
<li>Item 1
    <ul>
    <li>Sub Item 1
        <ul>
            <li> Sub Sub Item 1</li>
            <li>Sub Sub Item 2</li>
        </ul>
    </li>
    <li>Sub Item 2</li>
    </ul>
</li>
<li>Item 2</li>
</ul>

What I want is that, first level items (item 1, item 2), when hovered upon, has its background changed to color two. Then when sub item 1,2 are hovered upon, the background color changed to color 1. When sub sub item 1,2 get hovered upon, they changed to color 2 and so on as the nestin开发者_如何学编程g goes deeper. This means that for alternate levels of nesting, the background color alternates between two colors on hover as it goes deeper.

Any idea how to do this using jquery or css or both?


The problem you are having is that multiple hover events are fired when you hover over sub items. Since the sub is a part of the parent element, the parent is technically getting hovered too. You can fix this by wrapping the text of each item in an inline element like span. Now each list item only activates one hover event.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
.odd {color:red;}
.odd:hover, .odd:active{color:blue;}

.even{color:blue;}
.even:hover, .even:active{color:red;}
</style>
</head>
<ul>
<li><span class="odd">Item 1</span>
    <ul>
    <li><span class="even">Sub Item 1</span>
        <ul>
            <li><span class="odd"> Sub Sub Item 1</span></li>
            <li><span class="odd">Sub Sub Item 2</span></li>
        </ul>
    </li>
    <li><span class="even">Sub Item 2</span></li>
    </ul>
</li>
<li><span class="odd">Item 2</span></li>
</ul>


</html>


You can solve this with CSS. Give the main items a class of main and the sub items a class of sub and you can define

.main:hover
{
    color: Red;
}

.sub:hover
{
    color: Blue;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消