Вы можете сделать что-то вроде этого:
Версия 1: использовать transitionend
событие
const myArray = [
"text1",
"text2",
"text3",
"text4",
"text5"
],
container = document.querySelector("h1"),
transitionEndEvent = whichTransitionEvent();
let i = 0;
(function loop() {
// Add the "hide" class
setTimeout(()=> container.classList.add('hide'), 0);
// Wait for the animation to end
addEventListenerOnce(container, transitionEndEvent, () => {
// Change the text
container.innerHTML = myArray[i];
// Remove the class
container.classList.remove('hide');
// Wait for the animation to end
addEventListenerOnce(container, transitionEndEvent, () => {
i = ++i % myArray.length;
// Show the text for 1 second and continue
setTimeout(loop, 1000);
});
});
})();
// Just a utility function to trigger an event handler once
function addEventListenerOnce(el, eventName, callback) {
el.addEventListener(eventName, handler);
function handler() {
el.removeEventListener(eventName, handler);
callback.call(el);
}
}
// The name of the event depends on the browser
function whichTransitionEvent(){
var t, el = document.createElement("fakeelement");
var transitions = {
"animation" : "transitionend",
"OAnimation" : "oTransitionEnd",
"MozAnimation" : "transitionend",
"WebkitAnimation": "webkitTransitionEnd"
}
for (t in transitions){
if (el.style[t] !== undefined){
return transitions[t];
}
}
}
h1{
opacity: 1;
transition: opacity 300ms;
}
.hide {
opacity: 0;
}
<h1></h1>
О функции whichTransitionEvent
Браузеры имеют разные имена для transitionend
событие . Эта служебная функция выберет правильную для текущего браузера. Я нашел вдохновение для этого здесь .
О функции loop
Как вы можете видеть, эта функция заключена в (function loop() {...})();
. Это называется IIFE (выражение для немедленного вызова функции) . Мы вызываем функцию, как мы ее объявляем. В этом случае он также будет вызывать себя рекурсивно.
О строке i = ++i % myArray.length;
Здесь мы используем оператор по модулю сделать вещи короче. Но это эквивалентно следующему:
i++;
if (i >= myArray.length) { i = 0; }
Версия 2: использование setTimeout
В отличие от вышеприведенной версии, вам придется вручную редактировать продолжительность анимации в JS, если вы измените его в CSS. Но это удаляет много кода:
const myArray = [
"text1",
"text2",
"text3",
"text4",
"text5"
],
container = document.querySelector("h1"),
animationDuration = 300; // in milliseconds
let i = 0;
(function loop() {
// Add the "hide" class
container.classList.add('hide');
// Wait for the animation to end
setTimeout(function() {
// Change the text
container.innerHTML = myArray[i];
// Remove the class
container.classList.remove('hide');
// Wait for the animation to end
setTimeout(function() {
i = ++i % myArray.length;
// Show the text for 1 second and continue
setTimeout(loop, 1000);
}, animationDuration);
}, animationDuration);
})();
h1{
opacity: 1;
transition: opacity 300ms;
}
.hide {
opacity: 0;
}
<h1></h1>