Как сделать скрипт мультифункциональным?

Здравствуйте!

В двух словах - если скрипт, который с интервалом меняет классы поочередно для селектора

const txt = document.querySelector(".animate-text").children,
        txtLen = txt.length;
    let index = 0;
    const textInTimer = 3000,
        textOutTimer = 2800;

    function animateText() {
        for(let i=0; i<txtLen; i++){
            txt[i].classList.remove("text-in","text-out");
        }
        txt[index].classList.add("text-in");

        setTimeout(function(){
            txt[index].classList.add("text-out");
        },textOutTimer)

        setTimeout(function(){
            if (index === txtLen-1) {
                index = 0;
            } else {
                index++;
            }
            animateText();
        }, textInTimer);
    }

    window.onload=animateText;


Срабатывает для первого на странице элемента с классом .animate-text

Как поправить скрипт так, чтоб он срабатывал для каждого элемента на странице с классом .animate-text, а не только для первого?
  • Вопрос задан
  • 72 просмотра
Решения вопроса 1
modelair
@modelair
unsocial
вам нужен document.querySelectorAll('.animate-text') - выбирает все элементы с animate-text
const allChildren = document.querySelectorAll('.animate-text')
let index = 0

allChildren.forEach(elm => {
  for (let i = 0; i < elm.children.length; i++) {
      const child = elm.children[i]
    child.classList.remove('text-in', 'text-out')
  }
  elm.children[index].classList.add('text-in')
})
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы