问题
I have an image and i want the image to move where ever the touch input happens. basically the image should act as a virtual cursor. I already did for mousemove, but the same code doesn't works for touch move.
/*works for mouse move */
$(document).mousemove(function(e) {
$('img').offset({
left: e.pageX-55,
top: e.pageY-45
});
});
/* for touch move */
$(document).touchmove(function(e) {
$('img').offset({
left: e.pageX-55,
top: e.pageY-45
});
});
expected: image to follow cursor position in desktop and should follow touch position in touch devices.
回答1:
You may want to consider using .on() for binding.
function moveImg(e){
console.log(e);
$('img').offset({
left: e.pageX-55,
top: e.pageY-45
});
}
$(document).on({
mousemove: moveImg,
touchmove: moveImg
});
Remember touchmove is not supported by all browsers: https://developer.mozilla.org/en-US/docs/Web/API/Document/touchmove_event
pageX and pageY appear to be part of the touch event, yet if there are more than 1 touch points, it might cause some issues. See More: https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
The
TouchEventinterface encapsulates all of the touch points that are currently active. TheTouchinterface, which represents a single touch point, includes information such as the position of the touch point relative to the browser viewport.
I'm going to do some more testing and update the answer later if needed.
Update 1
Working example: https://jsfiddle.net/Twisty/hb0awzdy/
Mobile example: https://jsfiddle.net/Twisty/hb0awzdy/show/
touchmove event is looking for and potentially capturing multiple touch points. So to address this, we want to examine the first one and ignore the other.
$(function() {
function log(eObj) {
var str = eObj.type + " [" + eObj.top + "," + eObj.left + "]";
$("#results").html(str);
}
function moveCursor(e) {
var p;
var o = {
x: 55,
y: 45
};
if (e.type == "mousemove") {
p = {
left: Math.round(e.pageX - o.x),
top: Math.round(e.pageY - o.y),
type: e.type
};
} else if (e.type == "touchmove") {
var touch = e.changedTouches[0];
p = {
left: Math.round(touch.pageX - o.x),
top: Math.round(touch.pageY - o.y),
type: e.type
}
}
$('.cursor').css(p);
log(p);
}
$(document).on({
mousemove: moveCursor,
touchmove: moveCursor
});
});
As you can see, the event.changedTouches is an array of the various touch points and their attributes. If we focus on event.changedTouches[0], we can get the pageX and pageY details you're looking for.
Hope that helps.
来源:https://stackoverflow.com/questions/56875603/image-should-follow-touch-position-using-jquery-or-javascript