问题描述:

I am trying to have an whole page overlay, when mega menu is active. Curretly the function adds .show class to the overlay div, but it does not remove using the "else" function. Here is what I have:

HMTL:

<header>

<nav>

<ul>

<li>

<ul class="mega-sub-menu"></ul>

</li>

</ul>

</nav>

</header>

<div id="twc-page-overlay"></div>

CSS:

#twc-page-overlay {

position: fixed;

padding: 0;

margin: 0;

left: 0;

width: 100%;

height: 100%;

background: rgba(0, 0, 0, 0.58);

z-index: 50;

display: none;

}

.show {

display: block !important;

}

jQuery:

jQuery(document).ready(function($) {

$("div").click(function(){

if ( $('.mega-menu-item').hasClass('mega-toggle-on') ) {

$('#twc-page-overlay').addClass('show');

}

else {

$('#twc-page-overlay').removeClass('show');

}

});

});

Any help you be much appreciate!

Thanks!

网友答案:

If all .show does is toggle display of your element, you don't need it. .toggle() will toggle display from none to block:

$("#toggleOverlay").on('click', function(e){
  e.preventDefault();
  $('#twc-page-overlay').toggle();
})
#twc-page-overlay {
    position: fixed;
    padding: 0;
    margin: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 50;
    display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">


<a href="#" class="btn btn-default" id="toggleOverlay" style="margin: 20px;">Toggle Overlay</a>

<div id="twc-page-overlay"></div>
网友答案:

You never change the meta-toggle-on class on .mega-menu-item. Therefore, your if statement will always be true, even when executed multiple times

网友答案:

May you can use toggle ?

.toggleClass('active');

If you wanna toggle it:

.toggle();
相关阅读:
Top