为什么我的jQuery菜单会在点击链接之前消失?

时间:2015-08-07 06:31:15

标签: jquery

我正在编写一个jQuery下拉菜单。我将鼠标悬停在链接上,菜单应该出现......并且确实如此。问题是在我进入菜单链接之前菜单关闭了。除非鼠标离开菜单或顶级链接,否则菜单不应消失。我应该这样做吗?

{{1}}

这是jsFiddle

3 个答案:

答案 0 :(得分:3)

为什么选择jQuery?当你可以在纯CSS中做到这一点。

nav ul li:hover ul {
    display:inline;
}

演示:Fiddler

答案 1 :(得分:2)

这是因为mouseover id绑定到锚元素,并且ul不是它的子元素,所以当你移动到子菜单时它会关闭。

将您的选择器更改为:

$(this).mouseover(function(){
    console.log('hovered');
    $(this).parent().find('ul').css('display', 'inline');
})
.mouseout(function(){
    $(this).parent().find('ul').css('display', 'none');
});

并且可以正常工作。

演示:http://jsfiddle.net/IrvinDominin/oypo3vrm/1/

答案 2 :(得分:0)

$(function(){
    $('nav ul li:has(ul)').each(function(){
        //Prevent the links that have submenus from being clicked
        $(this).children('a').on('click', function(e){
            e.preventDefault();
        });
        //you don't need li in here
        $(this).mouseenter(function(){
            console.log('hovered');
            $(this).parent().find('ul').css('display', 'inline');
        })
        .mouseleave(function(){
            $(this).parent().find('ul').css('display', 'none');
        });
    });
});