gpt4 book ai didi

javascript - hammer.js 和 preventDefault();

转载 作者:搜寻专家 更新时间:2023-11-01 04:37:28 26 4
gpt4 key购买 nike

js 也支持触摸手势。我正在为防止默认操作而绞尽脑汁。当我设置 event.preventDefaultevent.gesture.preventDefault() 或什至在锤子上应用参数 {prevent_defaults: true } 它只会触发默认 anchor 上的 Action 。我怎样才能防止这种情况和/或我做错了什么?!

代码片段;

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

最佳答案

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

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

如果您正在使用 tap 事件,并且想要防止点击/点击文档,您可以这样做。我们需要创建一个全局 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();
});

关于javascript - hammer.js 和 preventDefault();,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18225061/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com