将鼠标hover在该菜单上时,将Jquery slideDown菜单保持打开状态?

我的Jquery slideDown菜单遇到了一些困难。 当我将鼠标hover在触发slideDown事件的按钮上时,它可以完美地工作,但是当我将鼠标hover在滑动的子菜单上时,它会触发slideUp事件并关闭菜单。

我正在寻找一种方法来改变我的代码,以便在我将鼠标hover在初始按钮上以触发子菜单slideDown后,如果我在子菜单上徘徊,那么子菜单将保持打开状态直到我不再将鼠标hover在初始按钮子菜单上。我希望它足够清晰。

这是我到目前为止的Jquery,除了子菜单外,它的工作正常!

$(document).ready(function () { var menu = $('.menu') menu.hide(); $('#mainbutton').hover( function () { $('.menu').stop(true, true).slideDown(400); }, function () { $('.menu').stop(true, true).slideUp(400); } ); }); 

有什么建议? 我确定这很简单,我只是无法正确地说出我的问题以找到别人的解决方案u_u

感谢您提供的任何帮助!

编辑:这里是jsfiddle – http://jsfiddle.net/mXXEP/

这不是一个特别容易解决的问题(开箱即用),因为有多个元素依赖于彼此的状态才能正常工作。 我之前用setTimeout做过这个。

使用setTimeout来维护对变量的控制,该变量告诉每个hover事件要做什么。 只是把一个jsFiddle放在一起做你想做的事情(虽然我认为在mo的滑动部分有问题):

http://jsfiddle.net/3vL3a/

和JS / HTML:

 $(document).ready(function () { var menu = $('.menu') var timeout = 0; var hovering = false; menu.hide(); $('#mainbutton') .on("mouseenter", function () { hovering = true; // Open the menu $('.menu') .stop(true, true) .slideDown(400); if (timeout > 0) { clearTimeout(timeout); } }) .on("mouseleave", function () { resetHover(); }); $(".menu") .on("mouseenter", function () { // reset flag hovering = true; // reset timeout startTimeout(); }) .on("mouseleave", function () { // The timeout is needed incase you go back to the main menu resetHover(); }); function startTimeout() { // This method gives you 1 second to get your mouse to the sub-menu timeout = setTimeout(function () { closeMenu(); }, 1000); }; function closeMenu() { // Only close if not hovering if (!hovering) { $('.menu').stop(true, true).slideUp(400); } }; function resetHover() { // Allow the menu to close if the flag isn't set by another event hovering = false; // Set the timeout startTimeout(); }; }); 

HTML:

 
Hover over me!

这样做的简单方法是检查mouseleave是否为.menu div ,如下所示:

 $(document).ready(function () { var menu = $('.menu') menu.hide(); $('#mainbutton').mouseover( function () { menu.stop(true, true).slideDown(400); } ); $(".menu").mouseleave( function () { menu.stop(true, true).slideUp(400) }) }); 

小提琴