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

zz2j4svz  于 2024-01-07  发布在  jQuery
关注(0)|答案(1)|浏览(165)
  1. function wallpaperMediaPropertiesListener(event) {
  2. // reset animation
  3. test.stop(true);
  4. test.css('margin-left', 0);
  5. // set song title.
  6. test.text(event.title);
  7. var testWidth = test.outerWidth();
  8. // clone text
  9. $('.test-copy').remove();
  10. if (testWidth > $('#line1').width()) {
  11. test.clone().css({'margin-left': gap, 'font-size': '1.05vh'}).removeClass().addClass('test-copy').insertAfter(test);
  12. }
  13. // move text
  14. let speed = 5;
  15. function shiftingAnimation() {
  16. let timer = setTimeout(() => {
  17. test.animate({'margin-left': -(testWidth + gap)}, {
  18. duration: Math.abs((testWidth + gap) * 100 / speed),
  19. easing: 'linear',
  20. complete: function () {
  21. test.css({'margin-left': 0});
  22. clearTimeout(timer);
  23. shiftingAnimation();
  24. }
  25. });
  26. }, 3000);
  27. }
  28. // first execution
  29. if (testWidth > $('#line1').width()) {
  30. setTimeout(shiftingAnimation, 3000);
  31. }
  32. }

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

cotxawn7

cotxawn71#

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

  1. `function wallpaperMediaPropertiesListener(title) {
  2. // reset animation
  3. test.stop(true);
  4. test.css('margin-left', 0);
  5. // set song title.
  6. test.text(title);
  7. var testWidth = test.outerWidth();
  8. // clone text
  9. $('.test-copy').remove();
  10. if (testWidth > $('#line1').width()) {
  11. test.clone().css({'margin-left': gap, 'font-size': '1.05vh'}).removeClass().addClass('test-copy').insertAfter(test);
  12. }
  13. // move text
  14. let speed = 5;
  15. function shiftingAnimation() {
  16. let timer = setTimeout(() => {
  17. test.animate({'margin-left': -(testWidth + gap)}, {
  18. duration: Math.abs((testWidth + gap) * 100 / speed),
  19. easing: 'linear',
  20. complete: function () {
  21. test.css({'margin-left': 0});
  22. clearTimeout(timer);
  23. shiftingAnimation();
  24. }
  25. });
  26. }, 3000);
  27. }
  28. // first execution
  29. if (testWidth > $('#line1').width()) {
  30. setTimeout(shiftingAnimation, 3000);
  31. }

字符串
}`

展开查看全部

相关问题