简体   繁体   English

使用javascript检测触摸设备上的不活动状态

[英]Detect inactivity on touch devices with javascript

I've been researching and found code that detects inactivity(when the user doesn't touch the screen) after the user goes idle for x amount of time which works perfectly when using the mouse but when I try using this with touch screen devices, it doesn't detect my finger or work. 我一直在研究,发现了可以在用户闲置x倍的时间后检测到不活动(当用户不触摸屏幕时)的代码,这在使用鼠标时非常有效,但是当我尝试在触摸屏设备上使用它时,它无法检测到我的手指或工作。 I've added a lot of DOM events such as " touchstart ", " touchmove ", " touchend ", " touchcancel " and others but they don't seem to work either. 我添加了许多DOM事件,例如“ touchstart ”,“ touchmove ”,“ touchend ”,“ touchcancel ”等,但它们似乎也不起作用。 Here is my code 这是我的代码

var idleTime = 0;
    $(document).ready(function () {
      //Increment the idle time counter every minute.
      var idleInterval = setInterval(timerIncrement, 3000); 

      //Zero the idle timer on mouse movement.
      $(this).mousemove(function (e) {
        idleTime = 0;
      });
      $(this).keypress(function (e) {
        idleTime = 0;
      });
    });

    function timerIncrement() {
      idleTime = idleTime + 1;
      if (idleTime > 1) { 
        alert("ok");
      }
    }

I will adjust the timer (you sayd you want an update every minute but you set you setInterval to 3000 millisec and i will try with this: 我将调整计时器(您说过要每分钟更新一次,但是将setInterval设置为3000 millisec,我将尝试使用此方法:

var idleTime = 0;
$(document).ready(function () {
  //Increment the idle time counter every minute.
  var idleInterval = setInterval(timerIncrement, 60000); 

  //Zero the idle timer on mouse movement.
  $(this).mousemove(function (e) {
    idleTime = 0;
  });
  $(this).keypress(function (e) {
    idleTime = 0;
  });
  //Zero the idle timer on touch events.
  $(this).bind('touchstart', function(){
   idleTime = 0;
  });
  $(this).bind('touchmove', function(){
   idleTime = 0;
  });
});

function timerIncrement() {
  idleTime = idleTime + 1;
  if (idleTime > 1) { 
    alert("ok");
  }
}

尝试添加以下代码:

$(this).bind('touchstart touchmove click', function(){ idleTime = 0; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM