JQuery - 禁用滚轮直到动画完成

时间:2017-12-06 12:37:17

标签: javascript jquery

我正在尝试在鼠标滚轮事件上禁用鼠标滚轮,并且仅在操作完成后启用它。

$(window).on('DOMMouseScroll mousewheel', function (event) {

    //disable mousewhell until the following animation is complete

    $('.box').animate({
        margin: div_offset+'px 0 0 0'
    }, 500);

    //enable mousewhell

    return false;
});

我还希望代码在第一个之后忽略每个滚动,直到动画完成。在这种特殊情况下,即使用户在鼠标滚轮上滚动多个刻度,我也希望动画只完成一次。基本上在这种情况下,我希望鼠标滚轮在单个鼠标滚动“勾号”后禁用500毫秒,并且不会记录剩余的“滴答”(如果用户在这500毫秒内滚动10个滴答,我只想要一个动画,其余的被忽略)。 500毫秒后,我想再次启用鼠标滚轮。

我提前谢谢你。

2 个答案:

答案 0 :(得分:2)

我最初关闭这个问题是一个副本,但被告知它只回答了一半的问题。我重新打开它以添加建议的解决方案,以便在动画完成之前不再处理事件。

根据this SO post

中的建议使用动画complete

你应该可以做类似的事情:

var animating = false;

$(window).on('DOMMouseScroll mousewheel', function (event) {
    if(animating){
        return false;
    }

   animating = true;

    $('.box').animate({
        margin: div_offset+'px 0 0 0'
    }, 500, function(){
        animating = false;
    });
});

答案 1 :(得分:0)

您可以做的是将函数分配给DOM事件,然后在该代码的第一行中分配一个空函数(或“关闭”它)。然后,当动画完成时,只需将该函数重新分配给DOM事件。 像这样:

function test(event) {
    $(window).off('DOMMouseScroll mousewheel');
    //perform your scroll event
    $('.box').animate({
         margin: div_offset+'px 0 0 0'
    }, 500);
    sleep(500);
    $(window).on('DOMMouseScroll mousewheel',test);
}
$(window).on('DOMMouseScroll mousewheel',test);

这样可以解决问题,但它会让你的JS线程忙碌,你也可以这样做:

function test(event) {
        $(window).off('DOMMouseScroll mousewheel');
        //perform your scroll event
        $('.box').animate({
             margin: div_offset+'px 0 0 0'
        }, 500);
        setTimeout(500,function() {$(window).on('DOMMouseScroll mousewheel',test(event));});

    }
    $(window).on('DOMMouseScroll mousewheel',test);

基于弗兰斯回答:

function test(event) {
            $(window).off('DOMMouseScroll mousewheel');
            //perform your scroll event
            $('.box').animate({
                 margin: div_offset+'px 0 0 0'
            }, 500,function() {$(window).on('DOMMouseScroll mousewheel',test);});

        }
    $(window).on('DOMMouseScroll mousewheel',test);