How to get dropdown menu to open/close on click rather than hover?

后端 未结 5 1665
星月不相逢
星月不相逢 2021-02-06 07:32

I am very new to javascript and ajax/jquery and have been working on trying to get a script to open and close the drop menu on click rather that hover.

The menu in quest

相关标签:
5条回答
  • 2021-02-06 08:08
     $(function() {
         $("#lang-selector li:first").click(function(){
             $('ul:first',this).toggle();
         })
     });
    

    Using toggle will require you to click to open then reclick to close

    0 讨论(0)
  • 2021-02-06 08:13

    search this $("#lang-selector li").hover and replace with

    $("#lang-selector li").click
    
    0 讨论(0)
  • 2021-02-06 08:16

    I would do something like this...

    $(function() {
     $("#lang-selector > li").click(function() {
         $('ul:first',this).toggleClass('active');
     });
    });
    

    And, then, in the CSS add this:

    .active { display: block; }
    

    << EDIT: Removed "ul" from ".active" class for CSS rendering efficiency >>

    Also make sure that the sub-nav <ul> has "display: none;" on it by default in your CSS.

    This will make it so that clicking an <li> tag in #lang-selector, but not in any sub-nav <ul> tags will either open or close the sub-nav, depending on it's current state.

    If you're worried about the accessibility of having "display: none" on the sub-nav by default, you can do something like this...

     $(function() {
      $("#lang-selector li ul").addClass("hidden");
      $("#lang-selector li").click(function(e) {
          e.preventDefault();
          $('ul:first',$(this)).toggleClass('hidden active');
        });
     });
    

    << EDIT: Altered selectors to match example provided, turned "this" into jQuery object. >>

    And then also add this to the CSS

    .hidden { display: none; }
    

    In this scenario, you have the <ul> showing by default, then when the document loads, jQuery adds the "hidden" class to all of them to hide them, then on the click of the <li> it will toggle the hidden and active classes, displaying them or hiding them.

    You'll also need to remove your current "display: none" from your #lang-selector ul ul in CSS, otherwise it takes priority over the hidden / active classes.

    0 讨论(0)
  • 2021-02-06 08:24

    .hover, .click, .something, are all triggers, view this link:

    Jquery Events

    to learn more about events in Jquery!

    Ps: sushil bharwani (vote it), is right, just change your .hover by the .click

    0 讨论(0)
  • 2021-02-06 08:26

    if you need two functions for a click event, try .toggle

    i'm using this:

    $('.triggerlist').toggle(function(e) {
            e.preventDefault();
      $(this).find('ul').fadeIn();
        },function() {
      $(this).find('ul').fadeOut();
        });
    

    Which allows me to do more stuff on the 2 functions than just the .click with its 1 function.

    0 讨论(0)
提交回复
热议问题