简体   繁体   中英

Disable jQuery Dropdown for Mobile

My website has had nav dropdowns that I made with CSS but I've recently changed it to jQuery so it's animated. When it was CSS I was able to disable the dropdowns on the smallest breakpoints for mobile. But with jQuery I don't know how to do that. This is my dropdown code. What can I do to it to make it disable when the viewport gets small enough?

$(document).ready(function() {
    $('.nav > li').mouseenter(function() {
        $(this).children('.nav-content').slideDown(200);
    });

    $('.nav > li').mouseleave(function() {
        $(this).children('.nav-content').slideUp(200);
    });
});

This is the website as it is now:

http://mattboy115.github.io/scarymonkeyshow/index.html

You can check the size of the screen with $(window).width() and $(window).height()

So something like

$(document).ready(function() {
    if($(window).width() > 800){
        $('.nav > li').mouseenter(function() {
            $(this).children('.nav-content').slideDown(200);
        });

        $('.nav > li').mouseleave(function() {
            $(this).children('.nav-content').slideUp(200);
        });
    }
}); 

The answers given will work, but I'd recommend making a second nav for mobile and using media queries to make the right one show.

Just real simple HTML:

<div class="desktop-nav">
    [nav code]
</div>
<div class="mobile-nav">
    [mobile nav code]
</div>

then CSS:

@media screen and (min-width: [X]px) {
    .mobile-nav {
        display: none;
    }
}
@media screen and (max-width: [X]px) {
    .desktop-nav {
        display: none;
    }
}

then your jquery is solved by just applying the mouseenter to .desktop-nav:

$(document).ready(function() {
    $('.desktop-nav > li').mouseenter(function() {
        $(this).children('.nav-content').slideDown(200);
    });

    $('.desktop-nav > li').mouseleave(function() {
        $(this).children('.nav-content').slideUp(200);
    });
});

I am uncertain if you are looking to do this at a specific size or if you want it for mobile. For example you can use modernizer to detect if touch is enabled on the device:

Using Modernizr to test for tablet and mobile - Opinions wanted

you can also check user agents to match device types and apply your code that way:

What is the best way to detect a mobile device in jQuery?

You can then apply if it does or doesn't match your conditions based on your detection..

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