Básicamente, las dos primeras imágenes (image1, image2) de la matriz dependen de la primera cadena (String1) de la matriz. y otras dos imágenes en String2, por lo que quiero que string1 cambie después de 4 segundos, pero en este momento se cambian dos imágenes que relacionan string1 y así sucesivamente para string2 y sus imágenes.
<script> var text = ["String1", "String2"]; var backgroundImg=["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"] var counter = 0; var currentPos = 0; var elem = document.getElementById("animated-text"); var elembg = document.getElementById("animated-background"); var inst = setInterval(change, 4000); var bginst = setInterval(changeImage, 2000); function change() { elem.innerHTML = text[counter]; counter++; if (counter >= text.length) { counter = 0; // clearInterval(inst); // uncomment this if you want to stop refreshing after one cycle } } function changeImage() { if (++currentPos >= backgroundImg.length){ currentPos = 0; } elembg.style.backgroundImage = "url('"+backgroundImg[currentPos]+"')"; } </script>Por favor, compruebe estos códigos.
<script> var text = ["String1", "String2"]; var backgroundImg = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"] var elem = document.getElementById( "animated-text" ); var elembg = document.getElementById( "animated-background" ); var inst = setInterval( change, 4000 ); var bginst = setInterval( changeImage, 2000 ); var text_index = 0; var text_total = text.length - 1; function change() { elem.innerHTML = text[text_index]; if ( text_index == text_total ) { text_index = 0; } else { text_index ++; } } var bd_index = 0; var bd_total = backgroundImg.length - 1; function changeImage() { elembg.style.backgroundImage = "url('" + backgroundImg[bd_index] + "')"; if ( bd_index == bd_total ) { bd_index = 0; } else { bd_index ++; } } </script>