简体   繁体   中英

Prevent recursive CSS :hover effect

Consider the following css and html.

<?xml version="1.0" encoding="UTF-8"?>
<!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" xml:lang="en" lang="en">
<head>
    <title>Hover Test</title>
    <style>
        div {
            min-height: 20px;
            margin:20px;
            border: 1px solid #000;
            background-color: #fff;
        }
        div:hover {
           background-color: #000;
        }
    </style>
</head>
<body>
    <div>
        <div>
            <div></div>
            <div></div>
        </div>
        <div>
            <div></div>
            <div></div>
        </div>
    </div>
    <div>
        <div>
            <div></div>
            <div></div>
        </div>
        <div>
            <div></div>
            <div></div>
        </div>
    </div>
</body>
</html>

The resulting effect is that it shows the hover effect on all nodes the mouse is over regardless of child nodes.

The effect i am locking for is to show the hover effect on only the nodes the mouse is directly over. That is not show the hover effect on an element when the mouse is over a child node.

Is there a way to this in CSS alone?

If not i guess i could always use onmouseover an onmouseout event handlers and using a css class .hover or similar. Butt I would preferably find a solution that dont mutate the affected dom node and that is easily styleable with CSS.

If you only want the leaf nodes to gain a black background color, and you can ensure there will only be exactly three levels of nodes, you can do this:

div > div > div:hover {
   background-color: #000;
}

Otherwise you have to use JavaScript to set the background colors of the leaf nodes and their parent nodes.

Here's something using jQuery that works:

$('div').hover(function() {
    $(this).css('background-color', '#000');
    $(this).parents('div').css('background-color', '#fff');
}, function() {
    $(this).css('background-color', '#fff');
    $(this).parent('div').css('background-color', '#000');
});

Preview on jsFiddle

I guess this is not possible with CSS, because you have to select the parent node of the hovered element, like div:hover < div , but there is no parent selector < in CSS.

But it's easy to do with JavaScript events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM