首页 > 解决方案 > 如何区分滚动事件和长按事件?

问题描述

问题 :

SomeDomElement.addEventListener('touchstart', function preventLongPress(event) {
              
                  if (event.touches.length >=1) event.preventDefault();
                }, false);

如果我使用 : if (event.touches.length >=1) event.preventDefault();那么这可以防止长按事件但也会禁用滚动事件。

长按没有touchmovetouchend事件。

我想要什么:

防止长按但不防止滚动

注意:我只使用 vanilla Javascript,没有jQuery

标签: javascriptmobiledom-events

解决方案


希望这会帮助你。

document.addEventListener("touchstart", function(){
    detectTap = false;
});
document.addEventListener("touchmove", function(){
    detectTap = true;
});
document.addEventListener("touchend", function(){
    if(detectTap)
        alert("scrolled"); /* here add whatever functionality you wants */
    else 
        alert("long pressed"); /* here add whatever functionality you wants */
});

推荐阅读