Toggle menu onclick, close by clicking menu link - but only in mobile view

限于喜欢 提交于 2019-12-12 03:16:51

问题


I've made a responsive menu for a one page website that switches to a toggleable menu, when the window width is lower than 768px. Basically I want the menu to be toggled by a click on the header and closed by another click on a menu link (li-element).

My jQuery code so far:

jQuery(document).ready(function() {
    var e = $("#pull");
    menu = $("#header ul"), $(e).on("click", function(e) {
        e.preventDefault(), menu.slideToggle()
    }), $(window).resize(function() {
        menu.is(":hidden") && menu.removeAttr("style")
    })
});
$("#header ul").on("click", "li", function () {
        $("#header ul").hide();
});

And a jsfiddle for demonstration: http://jsfiddle.net/ansoqvms/2/

So opening and closing the menu when clicking on the header works fine. I also got it working that the menu disappears when clicking a menu li-element.

Sadly the menu not only disappears in mobile view when a menu link is clicked, but also in normal view (> 768px).

I tried working with if($(window).width() < 768px), but it's not that cross browser happy.

I also tried solving the problem with if($('#pull').is(':visible')), since #pull is only visible in mobile view, but it didn't work out as well.


回答1:


I've been trying to recreate your problems with if($('#pull').is(':visible')) but for me the following works just fine.

jQuery(document).ready(function() {
    var e = $("#pull");
    menu = $("#header ul"), $(e).on("click", function(e) {
        e.preventDefault(), menu.slideToggle()
    }), $(window).resize(function() {
        menu.is(":hidden") && menu.removeAttr("style")
    })
});
$("#header ul").on("click", "li", function () {
    if($("#pull").is(":visible")) {
        //Use slideToggle() here for a better look and feel of the menu 
        $("#header ul").slideToggle();
    }
});

I don't see where your problem might be with this method but this should work just fine



来源:https://stackoverflow.com/questions/33107017/toggle-menu-onclick-close-by-clicking-menu-link-but-only-in-mobile-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!