javascript - 在 slideUp 动画结束之前再次触发函数时动画出现故障
问题描述
我使用以下脚本(以及外部 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);
});
}
其他代码资源:
Animate.css 用于 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
类。
if(document.querySelector(notif_orig).classList.contains("animated")){
console.log("Concurrent animation prevented.")
}else{
anim(notif_orig, 'slideInDown', function() {
//...
}
推荐阅读
- firebase - Flutter Firebase 消息传递和 sqflite
- android - 已解决:Android,生成作为 BigInteger 接收的 Diffie Hellman 公钥(错误:无效的 DH 公钥)
- python - 试图在 Python3 中将 csv 格式的 str 用作 csv 对象
- php - 在 Laravel 中从具有 foreach 循环的选择标签传输数据
- knative-serving - knative 0.4 Serving - 修订名称
- batch-file - 净停止“服务”不分割日志行
- powershell - 带有 PowerShell 循环的 JSON 文件
- karate - 在空手道的同一场景中的多个呼叫中使用标头
- c# - 有没有办法在不使用 Exchange 服务的情况下从电子邮件消息 Mime 内容中提取附件?
- android - 将自定义属性添加到 android build.gradle 库项目并在应用程序项目中覆盖相同