hammer.js和preventDefault();

时间:2013-08-14 06:53:54

标签: javascript jquery events hammer.js

js也支持触摸手势。我正在试图阻止默认行动。当我设置event.preventDefaultevent.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();
    }
}

2 个答案:

答案 0 :(得分: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();
});

答案 1 :(得分:0)

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

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