jQuery:菜单在点击时出现/消失

我一直在寻找网络,我找不到解决方案。 我也是jQuery的新手。

我的情况:

我有一个导航栏,其中的每个链接激活/触发megamenu(每个链接都有自己的megamenu)。

我需要的:

我需要一种方法让每个链接激活它自己的megamenu,megamenu应该关闭时:

  1. 用户单击导航栏中的另一个项目。

  2. 用户单击导航栏中的相同项目。

  3. 用户点击megamenu中的“关闭按钮”(X)图形(为简单起见,未在HTML中显示)。

HTML:

  • Products & Services
    • Content here...
  • Support & Training
    • Content here...
  • Communities
    • Content here...
  • Store
    • Content here...

我已经看过’性能下拉菜单’的脚本,但问题是它关闭了点击hover触发的菜单,正如我所说,我是jQuery的新手,我无法想办法使其适应我的需要。

http://www.sohtanaka.com/web-design/examples/drop-down-menu/

任何帮助将不胜感激。

谢谢。

你会将一个点击处理程序附加到另一个项目/相同的项目/关闭按钮,它将读取如下内容:

 $(function(){ $('#top-nav span').click(function(){ divTrigger = $('#top-nav span').index(this); thisMegaMenu = $('.megamenu:eq('+divTrigger+')'); $('.megamenu').slideUp(200); if(thisMegaMenu.is(":not(':visible')")){ thisMegaMenu.slideDown(200); } }); $('.megamenu').append("x"); $('#closeButton').live('click',function(){ thisMegaMenu.slideUp(200); }); }); 

在这里尝试一下

我能够得到另一个像魅力一样的解决方案:

 $(function(){ //Megamenus $('#top-nav li').click(function(){//set up a click event for the li $(this).siblings('.active').click();//click any other lis which are active to close their menus $(this).find('.megamenu').toggle();//toggle the child megamenu $(this).toggleClass('active');//toggle a class so we can identify any open megamenus }); $('.megamenu').click(function(event){//hide the megamenu on load and set up a click event.. $(this).parents('li').click();//..that just clicks the parent li event.stopPropagation();//stop the click bubbling up to the parent li }); }); 

我现在的问题是哪两个解决方案更好用? 现在这是一个很好的问题:p

解决方案提供于: http : //codingforums.com/showpost.php?p = 1016305&posttcount = 2

对于Navbar中的每个更高级别的

  • ,给他们一个类似’navbar’的类。 然后你的jQuery看起来像这样:

     $('li .navbar').click(function() { if($(this).find('.megamenu').is(':visible')) { // Already open $(this).find('.megamenu').hide(); } else { // Close others first $('.megamenu').each(function() { $(this).hide(); }); $(this).find('.megamenu').show(); } }); 

    您只需要为“关闭”按钮添加单击处理程序。 注意,这是未经测试的代码,所以如果有问题请告诉我。