如何在jQuery中调整窗口大小时使clearInterval起作用?

问题描述 投票:0回答:1

我知道这个问题已经被问过很多次了,但是我尝试了一切,但仍然找不到解决方法。动画一旦启动,就无法停止调整浏览器的大小。正确的方法是什么?谢谢。

let x;

$(window).on('resize', function() {
    if ($(window).width() >= 980) {
        clearInterval(x);
    } else {
        x = setInterval(animation, 3000);
    }
});

function animation() {
    $('#media-container').delay(3000).animate({
        marginLeft: '-100%',
    }, 500).delay(3000).animate({
        marginLeft: '-200%',
    }, 500).delay(3000).animate({
        marginLeft: 0,
    }, 500);
}
jquery animation resize clearinterval
1个回答
0
投票

由于.stop(true,true),该问题得以解决:

setInterval(animation, 3000);

$(window).on('resize', function() {
    if ($(window).width() >= 980) {
        $('#media-container').stop(true, true);
        $('#media-container').animate({
            marginLeft: 0,
        });
        return;
    }
    animation();
})

function animation() {
    if ($(window).width() < 980) {
        $('#media-container').delay(3000).animate({
            marginLeft: '-100%',
        }, 500).delay(3000).animate({
            marginLeft: '-200%',
        }, 500).delay(3000).animate({
            marginLeft: 0,
        }, 500);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.