简体   繁体   English

jQuery下拉菜单使用toggle和hover()问题

[英]Jquery dropdown menu using toggle and hover() problem

So I am trying to create a drop down menu using .hover() and .toggle(). 所以我试图使用.hover()和.toggle()创建一个下拉菜单。 While Have managed to get the menu to appear when the user rolls over the link, it disappears when the user moves off the link to select an item from the menu. 当用户将鼠标悬停在链接上时,已设法使菜单出现,但当用户移开链接以从菜单中选择一项时,菜单消失了。 Is there a method or technique for keeping the menu toggled even when the user isn't still hovering over the link? 有没有一种方法或技术即使用户仍未悬停在链接上也能保持菜单切换?

Here is the JS: 这是JS:

<script type="text/javascript">
$(document).ready(function() {
$("#menu_link").hover(function () {
$("#the_menu").toggle();
});
});
</script>

将菜单元素放在链接内。

The solution can vary greatly depending on the HTML markup you're using. 该解决方案可能会因所使用的HTML标记而有很大差异。 But a general solution to these kinds of things is to let the body element detect "mouseenters" and detect which element the event originated from. 但是,解决这类问题的一般方法是让body元素检测“ mouseenters”并检测事件源自哪个元素。 If it's not either #menu_link or #the_menu , then hide the menu. 如果不是#menu_link#the_menu ,则隐藏菜单。

$("body").mouseenter(function (e) {
   var eventParents = $(e.target()).parents();
   if (eventParents.index($("#menu_link")) == -1 &&
         eventParents.index($("#the_menu")) == -1) {
      $("#the_menu").hide();
   }
});

$("#menu_link").mouseenter(function () {
   $("#the_menu").show();
});

This gives you flexibility in, for example, placing the menu link in a different container div to the menu itself. 例如,这使您可以灵活地将菜单链接放在菜单本身的不同容器div中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM