单击时删除当前元素上的悬停激活

时间:2013-06-28 18:01:21

标签: javascript jquery css user-experience

我有一个以两种方式工作的下拉菜单

  1. 经典CSS悬停
  2. 如果单击顶级li,它会使用jQuery在菜单中添加一个类,使菜单显示。
  3. 如果您通过点击事件打开菜单,我在菜单中有一个关闭按钮来关闭它。我想通过删除菜单上的类来实现。这是有效的,因为你仍然在菜单上盘旋,菜单不会消失,直到你盘旋不理想为止。我也尝试过使用.hide(),然后用CSS悬停功能搞砸了。

    jQuery中有没有办法删除元素的CSS悬停激活?下面是我如何使它工作,但我觉得如果我能解开CSS悬停,我可以用更少的JS来做。

        // Add class 'show' to .meganav__container. Visibility is controlled by CSS
        $('.meganav > li > a').on('click',function(){
            $('.meganav__container').removeClass('show');
            $(this).parents('li').children('.meganav__container').toggleClass('show');
        });
    
        // Closes menu when close button is clicked
        $('.subnav__container .close').on('click', function(){
            $(this).parents('.meganav__container').hide();
        });
    
        // For UX I'd like the menu to still work with hover
        $('.meganav > li').hover(
            function(){
                $(this).children('.meganav__container').show();
            },
            function(){             
                $(this).children('.meganav__container').hide();
            }
        );
    

    这就是我希望它工作的方式

    // Add class 'show' to .meganav__container. Visibility is controlled by CSS
    $('.meganav > li > a').on('click',function(){
        $('.meganav__container').removeClass('show');
        $(this).parents('li').children('.meganav__container').toggleClass('show');
    });
    
    // Closes menu when close button is clicked
    $('.subnav__container .close').on('click', function(){        
        //Remove hover on parent li but this doesn't work
        $(this).parents('li').unbind('onmouseover').unbind('onmouseout');
        $(this).parents('.meganav__container').removeClass('show');
    });
    

    Fiddle with it

1 个答案:

答案 0 :(得分:1)

我已更新此fiddle

中的代码

基本上,我只在具有'hoverManagement'类的li上创建了CSS悬停触发器。

然后,我们需要确保无论何时将鼠标悬停在属于导航ul的'li'元素上,class属性都会设置为'hoverManagement',因此它可以触发CSS悬停。

.meganav > li.hoverManagement:hover .meganav__container, .meganav__container.show {
    display: block;
}

对于更新的Javascript,请参阅上面提到的小提琴。

相关问题