如果在移动设备上滚动,则防止单击链接 [英] Prevent clicking a link if scroll on mobile

查看:18
本文介绍了如果在移动设备上滚动,则防止单击链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很长的垂直链接列表,用户可以滚动浏览,如果用户滚动,我需要防止在此链接上触发 click 事件(触摸).

I have long vertical list of links that user can scroll through, and I need to prevent triggering a click event (touch) on this links if user scrolls.

在当前场景中,当用户通过点击链接开始滚动时,它还会触发链接上的 click.这显然很糟糕.那么,有什么办法可以防止这种行为吗?

In current scenario, when user start scrolling by tapping over the link, it also triggers a click on link. Which is obviously bad. So, is there any way to prevent such a behavior?

推荐答案

工作小提琴

在这种情况下,我们可以使用一个标志来防止在滚动期间发生 click 事件,并在滚动停止后启用它.

We could use a flag in this case to prevent click event just during the scroll and enable it after the scroll stop.

要监听滚动停止,您可以使用 jQuery 的 data 方法,该方法使我们能够将任意数据与 DOM 节点相关联,并使用 setTimeout() 函数将检查每 250 毫秒 如果用户仍然触发滚动,否则它将更改标志:

To listen on scroll stop you could use jQuery’s data method that gives us the ability to associate arbitrary data with DOM nodes and using setTimeout() function that will check every 250ms if the user still trigger the scroll, and if not it will change the flag :

var disable_click_flag = false;

$(window).scroll(function() {
    disable_click_flag = true;

    clearTimeout($.data(this, 'scrollTimer'));

    $.data(this, 'scrollTimer', setTimeout(function() {
        disable_click_flag = false;
    }, 250));
});

$("body").on("click", "a", function(e) {
    if( disable_click_flag ){
        e.preventDefault();
    }
});

希望这会有所帮助.

这篇关于如果在移动设备上滚动,则防止单击链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆