使用 JavaScript 确定平板电脑上的触摸位置 [英] Determine touch position on tablets with JavaScript

查看:83
本文介绍了使用 JavaScript 确定平板电脑上的触摸位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为元素"的对象.如果有人触摸平板电脑,我想返回触摸位置相对于对象的 x 和 y 坐标,即.e.对象左上角的坐标为 x=0 和 y=0.

I have an object with the name "element". If somebody touches the tablet, I would like to return the x and y coordinates of the touch position relative to the object, i. e. the upper left corner of the object has the coordinates x=0 and y=0.

我知道如何在台式机上实现这一点:

I know how to implement this on desktops:

$(function() {
$(document).mousedown(function(e) {
  var offset = $("#element").offset();
  var relativeX = (e.pageX - offset.left);
  var relativeY = (e.pageY - offset.top);
  alert(relativeX+':'+relativeY);
  $(".position").val("afaf");
});
});

所以我猜应该用touchstart"代替mousedown"这个词.但是,它仍然不起作用.

So the word "mousedown" should be replaced by "touchstart", I guess. However, it still doesn't work.

如何更改上述代码,使其适用于带有touchstart"而不是mousedown"的平板电脑?

How do I change the above code such that it works on tablets with "touchstart" instead of "mousedown"?

推荐答案

你必须明确地从事件中拉出一个 touches 对象,它不直接包含坐标.看看下面代码的第二行.

You have to explicitly pull a touches object out of the event, it doesn't contain the coordinates directly. Look at line two of the code below.

这是我一直用来获取触摸/指针坐标的代码:

Here is the code I always use to get touch/pointer coordinates:

    if(e.type == 'touchstart' || e.type == 'touchmove' || e.type == 'touchend' || e.type == 'touchcancel'){
        var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
        x = touch.pageX;
        y = touch.pageY;
    } else if (e.type == 'mousedown' || e.type == 'mouseup' || e.type == 'mousemove' || e.type == 'mouseover'|| e.type=='mouseout' || e.type=='mouseenter' || e.type=='mouseleave') {
        x = e.clientX;
        y = e.clientY;
    }

将它放在一个事件侦听器中,该侦听器侦听任何或所有这些事件并添加您的偏移量计算,这应该可以工作.

Put this inside an event listener that listens for any or all of those events and add your offset calculation and this should work.

这篇关于使用 JavaScript 确定平板电脑上的触摸位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆