简体   繁体   中英

Don't show hover state on touch devices

Is this possible? Short of converting all my hover styles into mouseover listeners is it possible to stop a touch device from triggering the CSS hover state?

I have an application that must work on both touch and pointer input, it works great but certain styles applied on hover just don't make sense on touch devices because they tend to retain the hover state indefinitely after a user has tapped an object.

Things to take into account:

  • Device width bears no correlation with touch enabled devices to me, the touch screens we are using here are desktop size monitors.

  • I don't want to force a user to input via touch on a multi-input device.

I had solved this problem following the approach shared in the link in the comments above. If you're not using it, consider using Modernizr in this scenario. Would like to hear some other approaches as well...

As user, Blender mentions, you can check against touch events like so:

html.touch {
  /* Touch Device ~ No Hovers */
}

html.no-touch {
  /* Not a Touch is disabled */
}
html.no-touch .element:hover {
   opacity:.5;
}

My solution is to add hover-active css class to the HTML tag, and use it on the beginning of all the CSS selectors with :hover and remove that class on the first touchstart event.

http://codepen.io/Bnaya/pen/EoJlb

JS:

(function () {
    'use strict';

    if (!('addEventListener' in window)) {
        return;
    }

    var htmlElement = document.querySelector('html');

    function touchStart () {
        document.querySelector('html').classList.remove('hover-active');

        htmlElement.removeEventListener('touchstart', touchStart);
    }

    htmlElement.addEventListener('touchstart', touchStart);
}());

HTML:

<html class="hover-active">

CSS:

.hover-active .mybutton:hover {
    box-shadow: 1px 1px 1px #000;
}

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