简体   繁体   中英

Disabling hover events on handheld devices

I have some fancy hover animations going on with my website. I want to disable them on handheld devices such as tablets and phones.

I know that I could use min/max-width to do this but I want to keep the effect in the browser on desktops at all viewport sizes. The reason I don't want it on mobile/tablets is simply because there is no mouse...hence...the hover effect won't translate as I want.

I have seen that you can detect specific user agent stylesheets? Or there are some scripts to do this? I have found a few but they aren't explained very well.

Modernizr wouldn't be able to do this would it? I ask because I saw it mentioned in a post when I was researching.

Thanks in advance :)

You can do it with JS and using a class. Example

HTML:

<a href="#" id="link">Homepage</a>

CSS:

#link {
    background: whitesmoke;
    border: 1px solid gainsboro;
    display: table;
    padding: 5px;
    transition: .5s;
}
/* hover won't work if the #link has a class "nohover" */
#link:not(.nohover):hover {
    background: skyblue;
    border: 1px solid dodgerblue;
}

Adding .nohover to the element when the screen width is less than the target device width. 500px in this case.

window.onresize = function() {
    if (window.innerWidth < 500) {
        document.getElementById("link").className = "nohover";
    } else {
        document.getElementById("link").className = "";
    }
}

You can use Modernizr.js library. Modernizr will check for touch support and attach a .no-touch class to the html tag if the device doesn't support touch, so you could do the following for your hover links:

.no-touch a:hover {
}

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