简体   繁体   中英

How do I get my menu back after using .toggle?

A button link is used to .toggle a menu when I resize to a smaller window (responsive design).

I can use the button to toggle the menu but how do I get the menu to come back after resizing to a bigger window (Example: I tilt my tablet/ mobile to landscape)?

http://jsfiddle.net/uzDP2/6/ (drag the window to resize)

HTML:

<img class="mobileicon" src="http://i.imgur.com/M7AiJ0P.png" width="40" height="29" alt="Mobile icon" />
<div class="menuframe">
    <a class="menu" href="#">Home</a>
    <a class="menu" href="#">Products and Services</a>
    <a class="menu" href="#">Other Link</a>
    <a class="menu" href="#">Image Gallery</a>
    <a class="menu" href="#">Links</a>
    <a class="menu" href="#">Contact</a>
</div>
<div class="menuframe"></div>

CSS:

.mobileicon {
    display: none;
}
@media (max-width: 400px) {
    .mobileicon {
        display: block
    }    
    .menuframe {
        display: none;
    }
}

Javascript:

document.querySelector(".mobileicon").addEventListener("click", function(){
    $(".menuframe").toggle();
    });

Because .toggle() will add an inline css to the element and that will override the css of the class. I suggest you use .toggleClass() for this problem.

http://jsfiddle.net/b_m_h/uzDP2/9/

jQuery:

document.querySelector(".mobileicon").addEventListener("click", function(){
    $(".menuframe").toggleClass('visible');
});

CSS:

.mobileicon {
    display: none;
}
.menuframe {
    display: block;
}
.visible{
    display: block !important;
}
@media (max-width: 400px) {
    .mobileicon {
        display: block
    }    
    .menuframe {
        display: none;
    }
}

You can do the following:

Add this to your CSS to add a display for your frame again:

@media (min-width: 400px){

    .menuframe{
        display:block;    
    }

}

You can also add a jQuery listener for the event-changed, to fire for a specific width:

$(window).resize(function() {
    if($(window).width() > 400){
        $(".menuframe").show();        
    }
});

This should fix your problem.

I think you can work on window resizing whit some checking.

$(window).resize(function(){
    if(IwantToToggle){
        //toggle menu
    }
});

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