I'm listening to the mousemove
event to give a button a nice effect based on the mouse position. On mobile however, if I touch the button the event is fired aswell making the button jump to the position. I'd rather have the button ignore the event when it's done by touch but I'm struggling to understand how this can be achieved?
// The function is just a helper of mine (it ads addEventListener to the matched events
createEventListener('.hoverable', 'mousemove', function(e) {
// stripped out some calculations for simplicity reasons
const deltaX = 50;
const deltaY = 50;
const transformString = `translate3d(${deltaX}px, ${deltaY}px, 0)`;
this.style.mozTransform = transformString;
this.style.webkitTransform = transformString;
this.style.transform = transformString;
});
You could possibly add the CSS style: touch-action to your elements.
style="touch-action: none;"
or maybe add/remove events and cancel the action of that event:
So the order of events fired is: 1) touchstart 2) touchmove 3) touchend 4) mousemove 5) mousedown 6) mouseup 7) click.
Maybe something like this:
function handleTouch(e) {
e.preventDefault();
}
document.getElementsByClassName("hoverable").addEventListener('touchstart', handleTouch, false);
document.getElementsByClassName("hoverable").removeEventListener('touchstart', handleTouch);
You can detect if the event comes from a touch screen and block it.
function onMouseMove(e) {
if (e.sourceCapabilities.firesTouchEvents) return
// Do something
}
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.