简体   繁体   中英

css dropdown menu and javascript

I have this html structure used for a dropdown menu :

<ul>
    <li><ul>...</ul></li>
    <li>...</li>
</ul>

and the css:

li ul {display : none;}
li:hover ul {display : block;}

(this is base structure only).

When I select an item from the menu I'm loading something with ajax and I would like to close the opened submenu.

I've tried with jquery to hide the parent of the clicked element ("li" is the clicked element and "ul" is the parent), the element hides but it does not appear again at mouseover on it's parent. (because the li:hover ul css rule has changed).

Any sugestions about how I could handle this situation?

The reason that it doesn't work is that you hide the element by setting the style on the element itself, and that has higher priority than the style sheet.

Use a class instead of the hover: pseudo-class:

li ul {display : none;}
li.active ul {display : block;}

Set the class on the element when you hover the submenu:

$('ul li').hover(function() {
  $(this).addClass('active');
}, function() {
  $(this).removeClass('active');
});

Now you can remove the class from the element whenever you want, and it will not screw up the hover.

so if you're using javascript after all, you could make the following changes to the css:

li.hover ul {display : block;}

and the javascript:

$("ul li").hover(function(){ 
  $(this).addClass("hover"); 
}, function(){ 
  $(this).removeClass("hover"); 
});

Best way to solve this is by using Javascript to create the hover effect instead of CSS. This way you can hide the element every moment you want.

So, instead of li:hover ul {display : block;} , use:

$('li').each(function(){
   $(this).bind('mouseover',function(){
      $(this).find('ul').show();
   });
   $(this).bind('mouseout',function(){
      $(this).find('ul').hide();
   });
});

try that menu that i created a couple min ago:

http://jsfiddle.net/aL7Xe/40/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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