使用香草检测点击和触摸事件 javascript

detecting clicks and touch events with vanilla javascript

大家好。 我想获得第一次点击或触摸页面的时间戳。 此页面可以在普通浏览器或 webview 中加载,因此最好使用没有任何库的 vanilla javascript。

这有可能实现吗?或者我必须使用一些 jQuery 什么的? 我只想保存第一次互动的Date.now()

如果您只想听第一次点击,您可以像这样简单地做一些事情:

window.onclick = function() {
    var timeStamp = Date.now();
    console.log(timeStamp);
    //do manipulations, send data to server / anything you want to do

    //unbind window.onclick (resetting it to empty function)
    window.onclick = function() {}
}

您可以在 MDN
上阅读有关 onclick 的更多信息 注意 这将取消绑定 每个 onclick 绑定到 window 对象本身,因为您只能有一个这样的侦听器。然而,another methodwindow.onclick = function() { ... } 具有以下优势:

  1. It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla extensions that need to work well with other libraries/extensions.
  2. It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)
  3. It works on any DOM element, not just HTML elements.

所以这基本上允许您添加这样的事件:

//first event listener
window.addEventListener('click', function() { console.log('click1'); });
//second event listener (also a click)
window.addEventListener('click', function() { console.log('click2'); });

上面的例子会在控制台输出如下内容:

"click1"
"click2"

addEventListenerbrowser support 非常好,即使您需要支持较旧的浏览器,您也必须谨慎行事,因为不同浏览器会有不同的实现。

对于(大多数)触摸设备,点击会被转换为触摸,但会延迟 300 毫秒以检查是否有双击,这不是全部,但总体上实现得相当一致。

在 MDN 上有一些关于 Touch Web API but if you scroll down there is no real support for it yet, other libraries implement code that uses mouse events that are translated to clicks by devices and use that with some object wrapper to fire off custom touch events, Hammer.js 的内容是这些库之一 - 从某种意义上说,这个库可能更聪明一些,如果它们存在的话可能会使用真实的触摸事件,但我从未使用过 Hammer.js 之前。