且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在jQuery悬停菜单中保持子菜单打开?

更新时间:2022-11-16 17:03:46

我有一个类似的案例,并通过将mouseover事件拆分为单独的mouseenter和mouseleave事件来解决.只是伪代码/大纲,但在您的情况下,请尝试类似以下操作:

I had a similar case, and solved it by splitting up the mouseover event into separate mouseenter and mouseleave events. Just pseudocode / an outline, but with your case try something like:

$("div#main-nav div").mouseenter(function() {
   // Check if sub menu is open, return if it is allready open
   // (I add a 'menu_open' class to sub menu when it is opened)

   // Code to hide open submenues
   // Code to open selected submenu      
});

然后使用mouseleave及其事件的toElement属性检查鼠标指针的去向,如果它进入子菜单,则不执行任何操作,如果不关闭所有子菜单,则不执行任何操作.请注意,您还需要在子菜单上挂接mouseleave事件.像这样:

Then use mouseleave and the toElement property of its event to check where the mousepointer went, if it went to a sub menu, do nothing, if not close all sub menues. Note that you need to hook up mouseleave events on the sub menues too. Something like this:

$("#main-nav div").mouseleave(function (event) {
   var toElem = $(event.toElement);
   if (toElem.closest("div.sub-nav").id=="subnav") return; // Prob nicer way to do this...point is to check if mouse enters a submenu, and if so stay open.
   // Close all open submenues, e.g. 
   $("#sub-nav ul").hide();
 });

 $("#subnav ul").mouseleave(function (event) {
    var toElem = $(event.toElement);
    if (toElem.closest("div.sub-nav").id=="subnav") return; // Check if entering submenu
    if (toElem.closest("div#main-nav")) return; // Check if entering main menu
    // Close all open submenues, e.g.
    $("#sub-nav ul").hide();
 });

希望这对您有所帮助.只是自己解决了这个问题,所以还没有时间完善它,我敢肯定有更好,更漂亮的方法可以做到这一点.

Hope this is of some help to you. Just solved this myself, so haven't had time to polish it, I'm sure there are better and prettier ways to do this.