我在写一个jQuery下拉菜单。 我将鼠标悬停在链接上,菜单应该出现......并且确实如此。 问题是在我进入菜单链接之前菜单关闭了。 除非鼠标离开菜单或顶级链接,否则菜单不应该消失。 我应该这样做吗?
$(function(){ //Find all ul elements within items in the nav $('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(); }); $(this).children('a').mouseover(function(){ console.log('hovered'); $(this).parent().find('ul').css('display', 'inline'); }) .mouseout(function(){ $(this).parent().find('ul').css('display', 'none'); }); }); });这是一个jsFiddle
I am writing a jQuery dropdown menu. I hover over a link and a menu is supposed to appear... and does. The problem is that the menu closes before I get to a menu link. The menu should not disappear unless the mouse leaves the menu or the top level link. Should I be doing this differently?
$(function(){ //Find all ul elements within items in the nav $('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(); }); $(this).children('a').mouseover(function(){ console.log('hovered'); $(this).parent().find('ul').css('display', 'inline'); }) .mouseout(function(){ $(this).parent().find('ul').css('display', 'none'); }); }); });Here is a jsFiddle
最满意答案
这是因为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/
It's because the mouseover id bound to the anchor element, and the ul is not a children of it, so when you move to the submenu it closes.
Change your selector to:
$(this).mouseover(function(){ console.log('hovered'); $(this).parent().find('ul').css('display', 'inline'); }) .mouseout(function(){ $(this).parent().find('ul').css('display', 'none'); });and will work fine.
Demo: http://jsfiddle.net/IrvinDominin/oypo3vrm/1/
更多推荐
发布评论