我怎么能让hammer.js滑动事件在父元素上触发,而不是在一般的子元素上

How can I have a hammer.js swipe event fire on a parent element but not general child element?

本文关键字:元素 js 事件 怎么能 hammer      更新时间:2023-09-26

我使用的是hammer.js 2.0

我有一个容器,需要有滑动事件。然而,该容器有一个元素,它是一个旋转木马,包含自己的滑动通风口。我怎么能让这个滑动事件在旋转木马的任何地方触发?

var self = this,
    hammerContainer = document.querySelector('section.content-wrapper'),
    carousel = document.querySelector('.image-gallery-carousel'),
    hammerOpts = {
      threshold: 4,
      velocity: .3
    },
    hammer = new Hammer(hammerContainer, hammerOpts);
Hammer.off(carousel, 'swipeleft swiperight', function () {
});
hammer.on('swipeleft', function (e) {
// do some other things
});

.off方法似乎在我的旋转木马上不起作用。锤子事件仍在传播??冒泡?

它不需要只向旋转木马开火,也不需要向它可能拥有的任何孩子开火。

我发现的唯一工作方法是让jQuery参与进来。我觉得自己不是一个更好的人。

  1. 抓斗event.target
  2. 使用jQuery的.parents()方法获取具有给定类名的所有目标的父对象
  3. 使用if语句检查这些父对象的长度,如果长度为0,则执行我的滑动
  4. 使用属性选择器检查单词carousel作为类名的所有实例和变体,例如:[class*="carousel"]

    var self = this,
      hammerContainer = document.querySelector('section.content-wrapper'),
      hammerOpts = {
        threshold: 4,
        velocity: .3
      },
      hammer = new Hammer(hammerContainer, hammerOpts);
      hammer.on('swiperight', function (e) {
        if (!$(e.target).parents('[class*="carousel"]').length) {
         //do swipey things   
        }
      });
    

我觉得事件传播应该是我能够做的事情。比如,调用e.stopPropagation()

有人,任何人,请给我一个更好的方法。