简体   繁体   中英

CSS Drop Down Menus on Responsive Site are Causing Problems on Mobile Phones

I have been tasked with taking a site that uses CSS drop down menus and making it responsive. Since mobile phones don't have hover events I am using Modernizr to add classes to the menus to show/hide them. This works fine. The problem is that touching the parent element still results in the phone navigating to the parent element so unless you are super fast, you can't click on the sub items that appear in the menu. Return false and preventDefault both work on my iphone simulator but fail on real devices (android and iphone).

//make sure main nav links don't take you anywhere on mobile

$('#a-popular-main-nav').on('touchend', function(event) {
    event.preventDefault();
    return false;
});

$('#a-profile-main-nav').on('touchend', function(event) {
    event.preventDefault();
    return false;
});


if (Modernizr.touch) {
    $('.menu').each(function () {
        var $lis = $(this).find('li');
        $lis.on('touchend', function(event) {

            var $this = $(this);
            if ($this.hasClass('activated')) {
                $this.removeClass('activated');
            }
            else {
                $lis.removeClass('activated');
                $this.addClass('activated');
            }
            event.stopPropagation();

       });

        //close menus if touched outside the menu
       $('body').on('touchend', function() {
               $lis.removeClass('activated');
       });


    });

};

I've tried every combination of stopPropagation, preventDefault, and return false. Has anyone run into this before?

So the answer lies in the first bit of code. The trouble is the touchend event. The default that I am trying to prevent actually belongs to the click event so here is how I altered the code. Pretty easy fix.

$('#a-popular-main-nav').on('click', function(event) {
    event.preventDefault();
});

$('#a-profile-main-nav').on('click', function(event) {
    event.preventDefault();
});

I've done a fair amount of responsive design and have found the best solution in this is Chris Coyier's method of having a select menu for mobile. That way you can take advantage of each individual phone's native handling of the select menu, which will in most cases function much better (and more importantly predictably ) than any jQuery hacks.

http://css-tricks.com/convert-menu-to-dropdown/

Hope that helps

I've been looking into a responsive css drop down menu lately. This drop down seems to work fine on my iPhone: http://matthewjamestaylor.com/blog/centered-dropdown-menus#

But needs some styling work and a bug taken care of (on of the lis seems to move when you "hover"/click on a certain li Good luck.

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