How to Change Style of Parent <li> on Hover

随声附和 提交于 2019-12-10 16:59:01

问题


I have a WordPress site (on my localhost) that uses a <ul> for a custom menu. How can I change the CSS of a <li> on hover only if it has a <ul> sub-menu?

All the main menu items have a border-radius and I want to remove this on the current item (Services, below) for example:

    <div class="main-nav">
      <ul class="menu" id="menu-main-nav">
        <li><a href="#">Home</a></li>
        <li><a href="#">Services</a>
          <ul class="sub-menu">
            <li><a href="#">Item One</a></li>
            <li><a href="#>Item Two</a></li>
          </ul>
        </li>
        <li><a href="#>Contact</a></li>
      </ul>
    </div>

I can't find a CSS solution and I've tried jQuery too:

    $('ul.sub-menu').parent().hover(function(){
    $(this).addClass('no-radius');
}); 

回答1:


$('.menu li').has('ul').hover(function() {
    $(this).addClass('hover');
}, function() {
    $(this).removeClass('hover');
});



回答2:


$(".menu LI").hover(
    function() {
        if ($("UL", $(this)).length > 0) {
            $(this).addClass("no-radius");
        }
    },
    function() {
        $(this).removeClass("no-radius");
    }
);



回答3:


Does this help:

$("li").hover(function(){
if($(this).parent().hasClass("sub-menu") {
 $(this).css("color", "red");
}
});



回答4:


$('ul.sub-menu').parent().hover(function(){
    $(this).parent().addClass('no-radius');
});

You can always use console.debug($(this)) to check which element you are accessing




回答5:


$('li>ul.sub-menu').hover(function() {
    $(this).addClass('no-radius');
}, function() {
   $(this).removeClass('no-radius');
});

In Your solution this refers to the ul item and not its parent.

Instead this piece of code checks if any li has a direct child of ul with class=sub-menu and then applies the desired class to the li element.

Hope it helps,

Cheers!



来源:https://stackoverflow.com/questions/8180378/how-to-change-style-of-parent-li-on-hover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!