简体   繁体   中英

Hide Div When Clicked

I've got a little HTML/CSS/JQuery drop down menu working. My pseudo code for it is:

 function closeMenus() { $('.subMenu').css('display', 'none'); } 
 #mainMenu ul li .subMenu { display: none; position: absolute; } #mainMenu ul li:hover .subMenu { display: block; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="mainMenu"> <ul> <li> Menu Header <div class="subMenu" onClick="closeMenus();">Menu Content</div> </li> </ul> </div> 

The CSS works so when someone hovers over Menu Header, the subMenu appears below it and disappears when the mouse leaves the menu. My problem comes when a user clicks an item in the menu; I'd like to hide the menu. The JavaScript hides the menu fine but when the user mouses over the menu header again, it doesn't reappear. It appears that CSS won't override the JavaScript display property. Most, if not all, of the links won't be going to other pages, just calling more JavaScript.

Anyone have any ideas how to hide the sub menu on click so that it will be again visible, or do I need more Javascript to show the menu every time someone hovers?

Use JQuery more fully -- look into the .toggle() command and bind it via click:

$('.subMenu').click(function() {$(this).toggle();});

Then you can eliminate most of your other code.

Stryle attribute has highest priority.

$('.ftpBrowseSubMenu').css('display','none');

make

<div style="display:none">

, so rule

#mainMenu ul li:hover 

has lower priority against style attribute. So, you have to do everything with javascript.

Like you already said are element styles stronger than css styles (unless you use !important). So you have to to do everything with Javascript what shouldn't be to hard. You have just to register two more event listener: onmouseover and onmouseout. With them you can set the display property to the correct value and it will work this way.

You're trying to do half of it with CSS and half of it with jQuery. Just do it all with jQuery: http://jsfiddle.net/hw5qr/

$('.subMenu').click(function() {
    $(this).hide();
});

$('#mainMenu').hover(function() {
    $(this).find('.subMenu').show();
}, function() {
    $(this).find('.subMenu').hide();
});

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