简体   繁体   中英

How to distinguish click and touch events in Internet Explorer 10 / Windows Phone 8

I'm working on a project with a hover navigation.

Due to the nature of touch enabled devices, hover isn't really supported on them. For iOS and android I managed to disable all hover effects and simulate them through the "touchstart" event, which sets the right css properties. This works like a charm. If it is a "touchstart" event, it is a mobile device, otherwise probably a desktop.

Unfortunately Internet Explorer implements its own events, namely "MSPointerDown" and the like.

My problem is, that both IE versions (newest mobile and desktop) fire a "click" event, as well as two "MSPointerDown" events, one with the pointerType "touch", one with pointerType "mouse". I really can't wrap my head around how to find out, if the action was a real touch event or caused by the mouse, since both are triggered. I wanted to avoid a solution based on media-queries since large touchscreens are getting more and more popular.

I ran into a similar issue recently. I ended up adding the hover state with JavaScript instead of the :hover pseudo-class and then binding either a touchstart or a click event to reveal the sub menu if the main menu item doesn't have a the hover class .

$(document).ready(function(){
    var $menuItem = $( '.menu__item' );

    $menuItem.on( 'mouseenter', function(){
        $(this).addClass( 'hover' );
    });

    $menuItem.on( 'mouseleave', function(){
        $(this).removeClass( 'hover' );
    });

   // For touch devices
   $menuItem.on( 'click', function(e) {
       if ( !$(this).hasClass( 'hover' ) ) {
           $(this).addClass('hover');
       }
   });    
});

Check this quick codepen that I've created.

http://codepen.io/aspjg/pen/zKzEQV

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