为什么我的jQuery菜单在点击链接之前消失?(Why does my jQuery menu disappear before I click a link?)

编程入门 行业动态 更新时间:2024-10-21 19:48:10
为什么我的jQuery菜单在点击链接之前消失?(Why does my jQuery menu disappear before I click a link?)

我在写一个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/

更多推荐

本文发布于:2023-08-07 20:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465563.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:菜单   链接   jQuery   menu   link

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!