如何防止滚动时单击?

时间:2019-11-16 19:04:14

标签: javascript jquery

我有一个基于滚动的滑块。滑块是专门为自适应而制造的。但是从dekstop我有一个问题。当我开始滑动滚动时,我会自动单击链接。我该如何预防?

$('.js_slider-item').on('dragstart', function() {
    return false;
});

// slider
$('.js_slider-viewport').each(function() {
        var slider = $(this),
            sliderClosest = $(this).closest('.js_slider'),
            sliderMouse = false,
            sliderPos,
            sliderX,
            scroll,
            movePos,
            moveX,
            moveWalk;

        // mousedown
        slider.on('mousedown', function(e) {
            sliderMouse = true;

            sliderPos = slider.offset();
            sliderX = e.pageX - sliderPos.left;
            scroll = slider.scrollLeft();
        });

        // mouseleave
        slider.on('mouseleave', function(e) {
            sliderMouse = false;
        });

        // mouseup
        slider.on('mouseup', function(e) {
            sliderMouse = false;
        });

        // mousemove
        slider.on('mousemove', function(e) {
            if (!sliderMouse) return;
            e.preventDefault();

            movePos = slider.offset(),
            moveX = e.pageX - sliderPos.left,
            moveWalk = (moveX - sliderX) * 2;

            slider.scrollLeft(scroll - moveWalk);
        });
    });

https://jsfiddle.net/xLwDgZODc/52dwu7v9/17/

1 个答案:

答案 0 :(得分:0)

您可以添加事件侦听器,以将所有click事件转移到文档或窗口上,以使它不会在页面上的任何位置(文档/窗口)上执行默认行为

代码可能看起来像(示例代码-sudo代码)

// override the click all over the window 
$(document).on('click' function () {
  // console.log(' click is not allowed while scrolling');
alert('clicked blocked ');
})//

然后,一旦用户停止滚动,您就可以删除点击监听器

// remove event listener from document
$(document).removeEventListener("click",  function () {
  // console.log(' click is not allowed while scrolling');
alert('clicked blocked ');
});