jquery - 如何防止滑动触发点击?

标签 jquery events swipe

我使用TouchSwipe创建可滑动的图像列表。我将滑动事件绑定(bind)到图像,同时我还绑定(bind)了一个单击事件来打开图像的大版本。

我的问题是,如果我滑动,它也会触发点击事件。我试过tap instead of swipe但我无法让它发挥作用。之后我尝试了很多地方建议的 event.preventDefault()event.stopPropagation() ,但没有效果。我最终的解决方案尝试是取消绑定(bind)点击事件并在事件发生后重新绑定(bind)它,但是如果我在事件函数的最后绑定(bind)事件,它会再次触发点击。

$(".js-header-swipe-image").swipe({
    swipe:function(event, direction, distance, duration, fingerCount){
        $("#details").unbind('click');//Temporary unbind, otherwise the swipe's click would trigger the gallery opening.

        //Handling swipe direction.

        $('#details').on('click', '.js-header-swipe-image', function (){//Rebind the temporary unbinded event.
            console.log('click');
            $('#modal-gallery').modal('show');
        });
    }
});

有没有办法中止事件本身或在事件完成后调用函数,以便我可以在滑动完成后重新绑定(bind)单击,这样就不会触发重新绑定(bind)的单击?我也愿意接受任何其他解决方案。

最佳答案

我使用这段代码,以便只有在未滑动时才会触发按钮(在 touchend 上):

var startY;
var yDistance;

function touchHandler(event) {
    touch = event.changedTouches[0];
    event.preventDefault();
}

$('.button').on("touchstart", touchHandler, true);
$('.button').on("touchmove", touchHandler, true);

$('.button').on("touchstart", function(){
    startY = touch.clientY;
});

$('.button').on('touchend', function(){

    yDistance = startY - touch.clientY;

    if(Math.abs(yDist) < 30){

        //button response here, only if user is not swiping
        console.log("button pressed")
    }
});

关于jquery - 如何防止滑动触发点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19227527/

相关文章:

javascript - 在指定元素的第一部分和最后一部分插入元素

javascript - react 点击事件冒泡 "sideways",而不仅仅是 "up"

jquery - 向responsiveslides.js 添加触摸滑动

jquery - 如何使用 jQuery 创建动态交互式图像 map ?

jquery - 如何克隆值输入文件

javascript - 使用 ajax codeigniter 动态依赖下拉列表

javascript - 为页面上的每个 iFrame 添加 `load` 事件

javascript - 要在将元素添加到 DOM 之前向元素注册事件?

javascript - 使用 quo.js 触摸滑动坐标

xamarin - 在 Xamarin Forms 应用程序中,如何在 Android 中使用 TalkBack 时将焦点放在标签和图像等非交互式元素上