【问题标题】:Detect inactivity on touch devices with javascript使用 javascript 检测触摸设备上的不活动状态
【发布时间】:2019-03-09 23:36:44
【问题描述】:

我一直在研究并发现在用户闲置 x 时间后检测不活动(当用户不触摸屏幕时)的代码,这在使用鼠标时非常有效,但当我尝试通过触摸使用它时屏幕设备,它不会检测到我的手指或工作。我添加了很多 DOM 事件,例如“touchstart”、“touchmove”、“touchend”、“touchcancel" 等,但它们似乎也不起作用。这是我的代码

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");
      }
    }

【问题讨论】:

  • 定义“不活动”。我是不是盯着你的页面看了一会儿又重新阅读,而没有移动鼠标“不活动”?
  • 是的,对于一个含糊的问题很抱歉

标签: javascript jquery


【解决方案1】:

尝试添加此代码:

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

【讨论】:

  • 我尝试在屏幕上拖动手指,但它不起作用,但当我点击屏幕时它起作用了。这是为什么呢?
  • 您的第一个动作被浏览器解释为滑动 (touchmove),而第二个动作实际上是轻击 (touchstart)
  • 那么有什么方法可以检测您何时在屏幕上拖动手指?
  • 是的,这里有一些有用的信息:w3.org/TR/touch-events
  • 在绑定事件中添加touchmove即可。我加了。
【解决方案2】:

我会调整计时器(你说你想要每分钟更新一次,但你将 setInterval 设置为 3000 毫秒,我会试试这个:

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");
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多