【问题标题】:Animation glitches when function is triggered again before slideUp animation ends在 slideUp 动画结束之前再次触发函数时动画出现故障
【发布时间】:2019-08-11 05:08:23
【问题描述】:

我使用以下脚本(以及外部 animate.css),当我想显示特定通知时调用该脚本。这个想法很简单;触发时,动画 - (向下滑动)通知框,以及更改的通知消息。时间到时,再次设置动画(向上滑出)。一切正常,除了当我在上一个调用动画时重新触发通知功能时(在超时和上滑动画开始之间 - 请参阅代码中的注释)。

// notification
var timer = '';
var notif = $('#notif');
var notif_txt = $('#notif #notif_txt');
var notif_orig = '#notif';

function err_notif(text = 'Prišlo je do napake!') {

  clearTimeout(timer);
  notif[0].style.display = 'none';

  notif_txt.text(text);
  notif[0].style.display = 'inline-block';
  anim(notif_orig, 'slideInDown', function() {

    timer = setTimeout(function(){

    // if user re-triggers the notif() function in time between mark 1 and 2, it glitches out the notification system
    // mark 1

      anim(notif_orig, 'slideOutUp', function(){

        // mark 2
        notif[0].style.display = 'none';


      });

    }, 1500);
  });
}

其他代码资源:

用于 css 动画的 Animate.css https://raw.githubusercontent.com/daneden/animate.css/master/animate.css

anim() 函数(来自 animate.css 的 github 页面)

function anim(element, animationName, callback) {
    const node = document.querySelector(element)
    node.classList.add('animated', animationName)

    function handleAnimationEnd() {
        node.classList.remove('animated', animationName)
        node.removeEventListener('animationend', handleAnimationEnd)

        if (typeof callback === 'function') callback()
    }

    node.addEventListener('animationend', handleAnimationEnd)
}

【问题讨论】:

  • 当动画正在进行时... animated 类被添加到元素中。它在动画结束时被移除。因此,您可以使用它来阻止额外的anim() 调用。

标签: javascript jquery css-animations animate.css


【解决方案1】:

如果你想阻止一个并发动画,你可以检查元素是否已经有animated类。

if(document.querySelector(notif_orig).classList.contains("animated")){
  console.log("Concurrent animation prevented.")
}else{
  anim(notif_orig, 'slideInDown', function() {
  //...
}

【讨论】:

    猜你喜欢
    • 2015-01-23
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 2022-09-27
    • 2021-07-23
    • 2014-09-09
    相关资源
    最近更新 更多