简体   繁体   中英

jQuery hover over an li that excludes the children of the element

I have a Wordpress-menu with a submenu. I've added an arrow to the li element that has a submenu inside. When the mouse goes over the a inside the li it makes an hover animation with CSS. Now I wanted to extend the animation to the arrow that is inside a span element inside the a tag. I did it with jQuery,

$('nav ul li.menu-item-has-children').hover(function() {
    $('nav ul li a span.arrow').css('color', '#fff');
}, function() {
    $('nav ul li a span.arrow').css('color', '#be1722');
});

But when the submenu is opened and the mouse is over it, the arrow remains white. How can avoid this?

This is the structure of my menu:

<nav>
    <li class="menu-item-has-children">
        <a>Menu item with sub menu</a><span class="arrow">arrow</span>
        <ul>
            <li>
                <a>Sub menu link</a>
            </li>          
        </ul>
    </li>
</nav>

I tried also with this:

$('nav ul li.menu-item-has-children a').hover(function() {
    $('nav ul li a span.arrow').css('color', '#fff');
}, function() {
    $('nav ul li a span.arrow').css('color', '#be1722');
});

But if I hover an a tag in the submenu the function starts again and the arrow turns white.

Can anyone help me?

Your element is <span>arrow</span> ;. But span.arrow in $('nav ul li a span.arrow') searches for a <span> element with a class .arrow . And there is no such class assigned to your <span> element.

Use this:

<span class="arrow">arrow</span>

The selector $('nav ul li a span.arrow') searches for <span> inside(child of) <a> .

The span element is not the child of a but its sibling, use + instead of a space in the selector.

$('nav ul li.menu-item-has-children a').hover(function() {
    $('nav ul li a+span.arrow').css('color', '#fff');
}, function() {
    $('nav ul li a+span.arrow').css('color', '#be1722');
});

See Next adjacent Selector (“prev + next”)

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