如何在使用Android移动浏览器时获得连续的mousemove事件?

zho*_*shu 18 javascript jquery android

使用此代码:

<h2 id="status">
0, 0
</h2>

<script type="text/javascript">
   $('html').mousemove(function(e){
      $('#status').html(e.pageX +', '+ e.pageY);
   }); 
</script>
Run Code Online (Sandbox Code Playgroud)

在像Firefox这样的Windows浏览器中,当我移动鼠标时可以看到鼠标位置,但是当我在android(2.1)浏览器中运行此页面时,当我触摸屏幕时我无法获得连续事件,它只是触发事件时我点按屏幕,为什么?以及当我触摸屏幕时如何获得连续的鼠标移动事件?

Gar*_*een 24

使用该touchmove事件(在我的Android浏览器上使用Froyo),虽然它有一些问题 - 浏览器只在触摸释放时更新div,但事件仍然会触发每次触摸动作.这可以通过将代码更改为:

var x = 0;
$('html').bind('touchmove', function(e) {
    $('#status').html(x++); // Only updates on touch release
});
Run Code Online (Sandbox Code Playgroud)

这是由于Android浏览器中的一个错误 - 您需要调用event.preventDefault()以使其按预期工作:

var x = 0;
$('html').bind('touchmove', function(e) {
    e.preventDefault();
    $('#status').html(x++); // Only updates on touch release
});
Run Code Online (Sandbox Code Playgroud)

官方错误详情:此处提供

要检测当前的X和Y位置,您应该使用该event.touches对象:

$(window).bind('touchmove', function(jQueryEvent) {
   jQueryEvent.preventDefault();
   var event = window.event;
   $('#status').html('x='+event.touches[0].pageX + '  y= ' + event.touches[0].pageY);
});
Run Code Online (Sandbox Code Playgroud)

jQuery的创建它自己的事件对象的"版本",它不具备原生浏览器的性能,如.touches-所以你需要使用window.event替代


Luk*_*uke 6

在阅读了接受的答案后,或许处理触摸和鼠标正在进行的事件的最佳方法是这样的?

<div id="status">x, y</div>
<script>
    $('html').on("mousemove touchmove", function(e){
        $('#status').html(e.pageX +', '+ e.pageY);
        e.preventDefault();
    });
</script>
Run Code Online (Sandbox Code Playgroud)