jquery 当设置定时器运行时值发生变化时出现动画问题

zz2j4svz  于 5个月前  发布在  jQuery
关注(0)|答案(1)|浏览(57)
function wallpaperMediaPropertiesListener(event) {

    // reset animation
    test.stop(true);
    test.css('margin-left', 0);
    
    // set song title.
    test.text(event.title);
    var testWidth = test.outerWidth();
    
    // clone text
    $('.test-copy').remove();
    if (testWidth > $('#line1').width()) {
        test.clone().css({'margin-left': gap, 'font-size': '1.05vh'}).removeClass().addClass('test-copy').insertAfter(test);
    }
    
    // move text
    let speed = 5;
    function shiftingAnimation() {
        let timer = setTimeout(() => {
            test.animate({'margin-left': -(testWidth + gap)}, {
            duration: Math.abs((testWidth + gap) * 100 / speed),
            easing: 'linear',
            complete: function () {
                test.css({'margin-left': 0});
                clearTimeout(timer);
                shiftingAnimation();
            }
            });
        }, 3000);
    }

    // first execution
    if (testWidth > $('#line1').width()) {
        setTimeout(shiftingAnimation, 3000);
    }

}

字符串
event.title返回正在播放的歌曲名称。wallpaperMediaProperties将在歌曲更改时触发该函数。
当testWidth > #line1 width时,动画在3s延迟后开始。当动画结束时,它每次以3s延迟重复自己。如果event.title值改变,它重置动画并从第一个3s延迟开始,依此类推。
但问题是,当事件.标题值在3s延迟期间更改时,无论条件(testWidth > #line1)是真还是假,都将应用动画。

cotxawn7

cotxawn71#

将event.title作为参数传递,而不是event:
1 -在调用者函数中传递事件。title
第一个月
然后:

`function wallpaperMediaPropertiesListener(title) {

// reset animation
test.stop(true);
test.css('margin-left', 0);

// set song title.
test.text(title);
var testWidth = test.outerWidth();

// clone text
$('.test-copy').remove();
if (testWidth > $('#line1').width()) {
    test.clone().css({'margin-left': gap, 'font-size': '1.05vh'}).removeClass().addClass('test-copy').insertAfter(test);
}

// move text
let speed = 5;
function shiftingAnimation() {
    let timer = setTimeout(() => {
        test.animate({'margin-left': -(testWidth + gap)}, {
        duration: Math.abs((testWidth + gap) * 100 / speed),
        easing: 'linear',
        complete: function () {
            test.css({'margin-left': 0});
            clearTimeout(timer);
            shiftingAnimation();
        }
        });
    }, 3000);
}

// first execution
if (testWidth > $('#line1').width()) {
    setTimeout(shiftingAnimation, 3000);
}

字符串
}`

相关问题