在处理浏览器事件时,我开始将Safari的touchEvents应用于移动设备.我发现addEventListener个条件句堆积如山.This project can't use 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;
});

Is there a way to combine the two event listeners as in the JQuery example?例:

window.addEventListener('mousemove touchmove', this.mouseMoveHandler, false);

如有任何建议或小贴士,我们将不胜感激!

推荐答案

在POJS中,一次添加一个侦听器.为同一元素上的两个不同事件添加相同的侦听器并不常见.你可以编写自己的小函数来完成这项工作,例如:

/* Add one or more listeners to an element
** @param {DOMElement} element - DOM element to add listeners to
** @param {string} eventNames - space separated list of event names, e.g. 'click change'
** @param {Function} listener - function to attach for each event as a listener
*/
function addListenerMulti(element, eventNames, listener) {
  var events = eventNames.split(' ');
  for (var i=0, iLen=events.length; i<iLen; i++) {
    element.addEventListener(events[i], listener, false);
  }
}

addListenerMulti(window, 'mousemove touchmove', function(){…});

Hopefully it shows the concept.

Edit 2016-02-25

达尔加德的 comments 让我重新审视了这一点.我想,现在在一个元素上为多个事件添加同一个侦听器更常见,以涵盖使用中的各种接口类型,而Isaac的回答提供了一个很好的内置方法来减少代码(尽管代码更少本身并不一定是一个额外的好处).通过ECMAScript 2015箭头函数进行扩展,可提供:

function addListenerMulti(el, s, fn) {
  s.split(' ').forEach(e => el.addEventListener(e, fn, false));
}

A similar strategy could add the same listener to multiple elements, but the need to do that might be an indicator for event delegation.

Jquery相关问答推荐

使用动态类名的gm_addStyle?

ASP.NET Core 6 jQuery 验证不起作用

哪个 JQuery Select 器会排除与给定 Select 器匹配的父项的项目?

在文本框中的最后一个字符之后设置焦点

document.querySelector 一个元素中的多个数据属性

jQuery.parseJSON 单引号与双引号

JSLint 消息:未使用的变量

jquery click 不适用于 ajax 生成的内容

JavaScript style.display="none" 还是 jQuery .hide() 更高效?

我可以限制 JavaScript 中数组的长度吗?

如何使用 jquery 更改 onclick 事件?

Bootstrap 3.0 弹出框和工具提示

将字符串true和false转为布尔值

按文本 Select 链接(完全匹配)

Isotope 和 Masonry jQuery 插件之间的区别

如何重新加载/刷新 jQuery 数据表?

使用 Jquery 查找父 div 的 id

在jQuery中获取CSS规则的百分比值

使用 jQuery 获取鼠标单击图像的 X/Y 坐标

'touchstart' 事件是否有与点击事件相同的 e.PageX 位置?