将 jquery touchevent eventListener 转换为 vanillaJs

Convert jquery touchevent eventListener into vanillaJs

我正在尝试将一些用 jQuery 编写的代码转换为 vanillaJs,但我被 touchstart 事件阻止了。 这是旧代码:

var buttonMenu = $('.js-desktop-menu');
buttonMenu.on('click touch', function () {
  if ($(window).width() >= 992) {
    // Something
  } else {
    // Something else
  }
});

我改写成这样了:

const buttonMenu = document.querySelector('.js-desktop-menu');
const clickEvent = (function() {
  if ('ontouchend' in document.documentElement)
    return 'touchend';
  else
    return 'click';
})

buttonMenu.addEventListener(clickEvent, function(e) {
  if (window.innerWidth >= 992) {
    // Something
  } else {
   // Something else
  }
});

但是touchstart事件好像没有执行。我是不是做错了什么?

您需要调用函数来 return addEventListener()type 参数的字符串。现在,当需要字符串时,您正在传递函数引用。试试这个:

const buttonMenu = document.querySelector('.js-desktop-menu');
const getEventType = () => 'ontouchend' in document.documentElement ? 'touchend' : 'click';

buttonMenu.addEventListener(getEventType(), e => {
  if (window.innerWidth >= 992) {
    // Something
  } else {
    // Something else
  }
});

这里有两点需要注意。首先,我使用三元表达式和箭头函数使获取事件类型的函数更加简洁,但逻辑是相同的。

其次,您使用 querySelector() 暗示只有一个元素将存在于具有提供的选择器的 DOM 中,但您给它一个 class 选择器。请注意,如果您以后添加多个 .js-desktop-menu 元素,这可能会导致意外行为。