代码之家  ›  专栏  ›  技术社区  ›  Astro-Otter

将jquery TouchEventListener转换为vanillaJs

  •  0
  • Astro-Otter  · 技术社区  · 5 年前

    旧代码如下:

    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
      }
    });
    

    1 回复  |  直到 5 年前
        1
  •  3
  •   Rory McCrossan Hsm Sharique Hasan    5 年前

    类型 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 未来的元素。