hey, escribí un código JavaScript y logré que la imagen cambiara cada pocos segundos, pero el texto cambia junto con la imagen, pero no se muestra el texto correcto aquí está el código:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href= "https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <style> img{ height: 500px; width: 450px; } h1{ color: darkgreen; margin-top: 20px; font-family: Comic Sans MS, cursive, sans-serif; } .button{ margin-left: 45%; } </style> <script> function changeImage() { var img = document.getElementById("img"); img.src = images[x]; x++; if(x >= images.length) { x = 0; } setTimeout("changeImage()", 6000); } function changeText() { var txt= document.getElementById("message"); txt.textContent = text[y]; y++; if(y>= text.length){ y = 0; } setTimeout("changeText()", 6000); } var text = [], y=0; text[0] = "MSG1"; text[1] = "MSG2"; text[1] = "MSG3"; setTimeout("changeText()", 6000); var images = [], x = 0; images[0] = "image1.jpg"; images[1] = "image2.jpg"; images[2] = "image3.jpg"; setTimeout("changeImage()", 6000); </script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-3"></div> <div class="col-md-6"> <h1 id="message"> Hello </h1> <img id="img" src="image1.jpg" > </div> <div class="col-md-3"></div> </div> </div> </body> </html>¿Hay alguna manera eficiente de hacerlo? Mi objetivo es hacer de 3 a 5 imágenes en una página web html que cambien entre sí cada pocos segundos y cada imagen tenga un texto diferente encima.
Combine sus dos funciones en una, para que ambas cosas sucedan al mismo tiempo:
<script> function changeImageAndText() { var img = document.getElementById("img"); img.src = images[x]; var txt = document.getElementById("message"); txt.textContent = text[x]; x++; if (x >= images.length) { x = 0; } setTimeout("changeImageAndText()", 6000); } var text = [], images = [], x = 0; text[0] = "MSG1"; text[1] = "MSG2"; text[2] = "MSG3"; images[0] = "image1.jpg"; images[1] = "image2.jpg"; images[2] = "image3.jpg"; setTimeout("changeImageAndText()", 6000); </script>En lugar de mantener dos matrices, tenga una matriz de objetos, cada uno de los cuales contiene información de imagen y texto. A continuación, puede crear marcas que contengan ambos conjuntos de información a la vez en lugar de depender de dos funciones.
Este ejemplo de trabajo utiliza imágenes de dummyimage.com .
const data = [ { image: 'https://dummyimage.com/100x100/666/ff0', text: 'Image 1' }, { image: 'https://dummyimage.com/100x100/222/ff0', text: 'Image 2' }, { image: 'https://dummyimage.com/100x100/fff/000', text: 'Image 3' }, { image: 'https://dummyimage.com/100x100/a45/000', text: 'Image 4' }, ]; // Cache the element const div = document.querySelector('div'); // `carousel` is the main function into which we // pass the data function carousel(data) { // `loop` is what `setTimeout` calls every second // We initialise `count` to 0 function loop(count = 0) { // Create the HTML using a template string const html = ` <figure> <img src="${data[count].image}" /> <figcaption>${data[count].text}</figcaption> </figure>`; // Add the markup to the div div.innerHTML = html; // Reset the count if we've reached the // end of the array, otherwise increment it if (count === data.length - 1) { count = 0; } else { ++count; } // Call `loop` every second with the // updated `count` variable setTimeout(loop, 1000, count); } loop(); } carousel(data); <div></div>Información Adicional
La forma en que lo haría es esta:
const text = ["MSG1", "MSG2", "MSG3"]; const image = ["image1.jpg", "image2.jpg", "image3.jpg"]; const imageObj = document.GetElementById("img"); const textObj = document.GetElementById("message"); let counter = 0; function ChangeImage() { if (counter == text.length) { counter = 0; } textObj.innerText = text[counter]; imageObj.src = image[counter]; counter++; } setInterval(ChangeImage, 3000); // 3000 = 3 Seconds, 5000 = 5 seconds.Lo más importante que debe recordar es reducir la cantidad de veces que se repite, al recorrer una matriz (cuando el puntero será siempre el mismo) use la misma variable (en este caso, el contador)