如果event.title接收到一个新的字符串,即使动画正在进行中,我希望动画被中断,并重新启动与新字符串(检查是否(textWidth > $('#line2').width()
)的新字符串,宽度和复制是新字符串太)。
var testText = $('.test-text');
function wallpaperMediaPropertiesListener(event) {
// event.title receives a random string at a random time.
if (!event.title) {
testText.text('\u200B');
} else {
testText.text(event.title);
var textWidth = testText.outerWidth();
let gapSize = 30;
if (textWidth > $('#line2').width()) {
var testTextCopy = $('<div></div>')
.addClass('test-text-copy')
.css({
'margin-left': gapSize,
})
.insertAfter(testText)
.text(testText.text());
function animateText() {
testText.delay(1000).animate({
'margin-left': -(textWidth + gapSize)
}, {
duration: textWidth * 30,
easing: 'linear',
complete: function() {
testText.css('margin-left', 0);
animateText();
}
});
}
animateText();
}
}
}
window.wallpaperRegisterMediaPropertiesListener(wallpaperMediaPropertiesListener);
#line2 {
display: flex;
margin-bottom: 1.4vh;
width: 10vh;
background-color: aquamarine;
overflow: hidden;
white-space: nowrap;
clip-path: inset(0% 0%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="line2"><span class="test-text">this is the original text.</span></p>
1条答案
按热度按时间fjnneemd1#
要在值更改时重置动画,可以使用stop方法中断正在进行的动画,然后使用新字符串重新启动它。
字符串
animationInterval变量用于跟踪正在进行的动画。当接收到新字符串时,它会检查是否有正在进行的动画(设置了animationInterval),并使用**testText.stop()和clearInterval(animationInterval)停止动画。**之后,它会使用新字符串重新启动动画。
更新
问题是textWidth和testTextCopy在动画循环中没有正确更新。
型
您可以使用requestAnimationFrame对动画进行更平滑的控制。
型