我在遍历项目列表并通过 vanilla javascript 淡入淡出时遇到了困难。假设我有一个字符串列表 ["cat", "ball", "bat", "mouse"]。
我想遍历这些项目并一一显示。例如,首先我需要显示“cat”,然后继续显示“bat”。为了做到这一点,我必须先等到“猫”淡入,等待它淡出,然后显示“蝙蝠”。目前,我只是在使用 for 循环,循环会直接进入“鼠标”列表的末尾,而不是等待其他元素完成淡入淡出。
为了解决这个问题,我知道我需要使用异步编程、回调、promise API 等,但我并没有真正使用这些,所以我不知道如何实现这个解决方案。非常感谢有关如何将异步编程与“setInterval()”一起使用的任何帮助或说明。
这是我的代码片段:
var textarr = ["cat", "ball", "bat", "mouse"]
for(let i=0; i<textarr.length; i++){
var text_item = document.getElementById('text_item');
text_item.style.opacity = 0;
text_item.innerHTML = textarr[i];
// problem lies here; this is skipping to end of the list (mouse)
fadeIn(text_item);
}
//function borrowed from stack overflow to fadeIn elements
function fadeIn(element) {
var op = 0.1; // initial opacity
element.style.display = 'block';
var timer = setInterval(function () {
if (op >= 1){
clearInterval(timer);
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op += op * 0.1;
}, 100);
}
利用transitionend
@RwwL 在评论中提到的事件:
let display = document.getElementById('display');
const animals = ['dog', 'cat', 'mouse'];
let i = 0;
display.addEventListener('transitionend', function(event) {
if (i < animals.length) {
if (!display.classList.contains('fadeIn')) {
display.innerHTML = animals[i++];
}
display.classList.toggle('fadeIn');
}
}, false);
// Set timeout, otherwise the transition won't take effect (there are ways around this)
setTimeout(() => {
display.classList.toggle('fadeIn');
}, 1000);
#display {
color: #FFFFFF;
transition: color 1s ease-in;
}
#display.fadeIn {
color: #000000;
}
<div id="display">Animal Names Here</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句