5

js 也支持触摸手势。我正在努力防止默认操作。当我在锤子上设置event.preventDefault甚至event.gesture.preventDefault()应用参数{prevent_defaults: true }时,它只会触发锚点的默认操作。我怎样才能防止这种情况和/或我做错了什么?!

代码片段;

function initializeNavigation() {
    $("nav").hammer({prevent_defaults: true }).on("tap", "a", function(event) {
        event.preventDefault();
        event.gesture.preventDefault();
        var target = $(this.hash);
        scrollToTarget(target, 1200);
        // if there is an open detailItem then close it.
        if (detailItemOpen) {
            $("div." + detailItemOpen).slideUp();
        }
    })

    if (Modernizr.mq('only screen and (max-width: 767px)'))  {
        initializeMobileMenuAndSetButton();
    }
}
4

2 回答 2

1

考虑到 Hammer 2.0+event.gesture不再是 Event,而是一个简单的 Object。

event.gesture.srcEvent将不是 stopPropagation 的正确事件,因此它不起作用。

如果您正在使用该tap事件,并且想要防止单击/点击文档,您可以执行以下操作。我们需要创建一个全局点击处理程序来替换原始方法stopPropagationpreventDefault

function createHandler(event) {
  return {
    isHandled: false,
    _shouldStopPropagation: false,
    _shoulePreventDefault: false,
    stopPropagation: event.stopPropagation.bind(event),
    preventDefault: event.preventDefault.bind(event),
  }
}


function handleEvent(handler, node) {
  let clickHandler; 


  if (!handler.isHandled) {
    handler.isHandled = true;
    document.addEventListener('click', clickHandler = (event)=> {
      if (handler._shouldStopPropagation) {
        handler.stopPropagation();
        event.stopPropagation();
      }
      
      if (handler._shoulePreventDefault) {
        handler.preventDefault();
        event.preventDefault();
      }
      document.removeEventListener('click', clickHandler, true);
    }, true);
  }
}


// Create a global tap Event so we can replace the original functions
document.addEventListener('tap', (event)=> {
  let handler = createHandler(event);

  event.stopPropagation = function() {
    handler._shouldStopPropagation = true;
    handleEvent(handler);
  };
  event.preventDefault  = function() {
    handler._shoulePreventDefault = true;
    handleEvent(handler);
  }
}, true);

// Now we can use it.
document.addEventListener('tap', (event)=> {
  /* If you want to prevent Default */
  event.preventDefault();

  /* If you want to stop propagation */
  event.stopPropagation();

  /* If you want to do both */
  event.preventDefault();
  event.stopPropagation();
});

于 2016-01-04T22:52:34.717 回答
0

我想你也可以试试event.stopPropagation()and event.gesture.stopPropagation()。但似乎 Hammer 给出了这种方法:event.gesture.stopDetect()对于类似的情况。

来源:https ://github.com/hammerjs/hammer.js/wiki/Event-delegation-and-how-to-stopPropagation---preventDefaults

于 2014-07-24T13:52:00.070 回答