当处理浏览器事件时,我开始使用Safari的touchEvents来处理移动设备上的事件。我发现addEventListener
与条件语句一起使用会导致堆积的问题。该项目不能使用jQuery。
一个标准的事件监听器:
/* option 1 */
window.addEventListener('mousemove', this.mouseMoveHandler, false);
window.addEventListener('touchmove', this.mouseMoveHandler, false);
/* option 2, only enables the required event */
var isTouchEnabled = window.Touch || false;
window.addEventListener(isTouchEnabled ? 'touchmove' : 'mousemove', this.mouseMoveHandler, false);
JQuery的bind
允许多个事件,使用方式如下:
$(window).bind('mousemove touchmove', function(e) {
//do something;
});
有没有一种方法可以像 JQuery 示例中那样组合这两个事件监听器? 例如:
window.addEventListener('mousemove touchmove', this.mouseMoveHandler, false);
欢迎提出建议或提示!
['mousemove', 'touchmove'].forEach(...)
。 - Dan Dascalescu['mousemove', 'touchmove'].forEach(function(event) { window.addEventListener(event, handler);});
不仅更易读,而且更快,因为它不需要拆分字符串并对结果数组中的每个项运行一个函数。 - Iharob Al Asimi