简体   繁体   中英

Is there a better way to handle a "hover" event on touch devices?

Is there a better way to handle a "hover" (this tapped, then effect active until something else is tapped) event on touch devices than using a global event handler to detect when the user taps something else?


For example, this code might work, but it relies on an event listener attached to the document body, so it's questionable performance-wise.

//note a namespace is used on the event to clear it without clearing all event listeners
$('myDiv').on('touchstart.temp', function () {
    //do stuff
    $('body').not(this).on('touchstart.temp', function () {
        //undo stuff
        $('body').not(this).off('touchstart.temp');
    });
});

In the future you should be able to use the touchenter and touchleave events, which apply to specific elements.

$("myDiv").on("touchenter mouseover", function() {
    // do hover start code
}).on("touchleave mouseleave", function() {
    // do hover end code
});

But according to MDN , this is just a proposal which hasn't been implemented yet.

If you use jQuery Mobile, you can use the vmouseover and vmouseleave events, which simulate the mouse events on mobile devices.

The Javascript onmouseover and onmouseout events work just fine! :)

It won't work on mobile devices, but I believe you anticipated that.

Edit: I also noticed you included the JQuery tag. You could also use the JQuery hover method if it is to your liking.

ie

$('div').hover(function(){
    $(this).css('background-color', 'red');
    }, function(){
    $(this).css('background-color', 'blue');
});

Example: https://jsfiddle.net/sofdz0s2/

As for hovering on all touch devices, it is not constant between all touch devices. Mine does not keep hovering after a tap. (I tried tapping on the div that changes and then on the green div, but it kept hovering after a tap.)

Edit 2:

As talked about in the comments, touchenter and touchleave are probably what you want.

I hope this helps!

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