将jquery TouchEventListener转换为vanillajs

6ljaweal  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(167)

我正试图将一些用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事件似乎未执行。我做错什么了吗?

wkftcu5l

wkftcu5l1#

您需要调用函数以返回中类型参数的字符串 addEventListener() . 现在,当需要字符串时,您正在传递函数引用。试试这个:

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中只存在一个元素,但您给它一个类选择器。如果您添加了多个,请小心这可能会导致意外行为 .js-desktop-menu 未来的要素。

相关问题