在动画过程中禁用单击

disable click during animation

本文关键字:单击 过程中 动画      更新时间:2023-09-26

我想在动画过程中禁用对元素的单击,当动画结束时,再次启用它。 这是代码:

$(document).on('click touchstart', '.slot1-up', function(e){
                e.preventDefault();
                firstSlotPos = parseInt($(".jSlots-wrapper:nth-child(1) .slot").css('top'));
                console.log(firstSlotPos)
                if (firstSlotPos < -309) {
                    $(".jSlots-wrapper:nth-child(1) .slot").stop(true,true).animate( { 'top' : firstSlotPos  + 310 + "px" },600, 'easeInOutSine', function() {
                    });
                }
        });
您可能会使用

off/on 动态添加/删除事件钩子,但这可能会变得混乱。

我的首选方法是在元素上存储一个data属性,以显示其状态。由此,您可以确定是否允许执行处理程序函数。像这样:

$(document).on('click touchstart', '.slot1-up', function(e){
    e.preventDefault();
    var $el = $(this);
    if (!$el.data('animating')) {
        var $slot = $(".jSlots-wrapper:nth-child(1) .slot");
        $el.data('animating', true);
        firstSlotPos = parseInt($slot.css('top'));
        if (firstSlotPos < -309) {
            $slot.stop(true,true).animate({ 'top' : (firstSlotPos + 310) + "px" }, 600, 'easeInOutSine', function() {
                $el.data('animating', false);
            });
        }
    }
});

只需使用伪选择器检查它:animated:

$(document).on('click touchstart', '.slot1-up', function (e) {
    e.preventDefault();
    // if animated, return {undefined}
    if($(".jSlots-wrapper:nth-child(1) .slot").is(':animated')) return;       
    firstSlotPos = parseInt($(".jSlots-wrapper:nth-child(1) .slot").css('top'));
    if (firstSlotPos < -309) {
        $(".jSlots-wrapper:nth-child(1) .slot").stop(true, true).animate({
            'top': firstSlotPos + 310 + "px"
        }, 600, 'easeInOutSine', function () {
        });
    }
});