Estoy trabajando en una presentación de diapositivas de JavaScript pero no estoyseguro de cómo agregar un título a cada imagen, el botón anterior no funciona correctamente (no muestra imagen después de dos o más clics) y también cómo podría ir a la primera y última imagen de las diapositivas.
var index=4;
var titles=[1,2,3,4,5];
// LIST OF CAPTİONS
caption[0] = "Caption for the first image";
caption[1] = "Caption for the second image";
caption[2] = "Caption for the third image";
caption[3] = "Caption for the first image";
caption[4] = "Caption for the second image";
caption[5] = "Caption for the third image";
function NextSlide()
{
if (index >= 5){index=0}
var img = document.getElementById("img1");
var slideName="images/img" + titles[index++] + ".jpg";
img.src=slideName;
}
function PrevSlide()
{
if (index >= 5){index=0}
var img = document.getElementById("img1");
var slideName="images/img" + titles[index--] + ".jpg"; img.src=slideName;
}
function last()
{
index = 1;
}
Respuestas
0 para la respuesta № 1El siguiente código da un ejemplo de cómo podríaimplementar los métodos first () y last (), así como cambiar el título. No ha proporcionado ningún HTML, por lo que puede necesitar pruebas / ajustes para ajustarse a lo que tiene (por ejemplo, deberá agregar un span
o p
etiqueta para contener el título con ID de caption1
)
var index = 3; // index for forth image as it"s zero based
// List of captions
var captions = ["Caption for the first image",
"Caption for the second image",
"Caption for the third image",
"Caption for the forth image",
"Caption for the fifth image",
"Caption for the sixth image"];
var slideShowImg = document.getElementById("img1");
var slideShowCaption = document.getElementById("caption1");
// Show current image
function showCurrentImage(){
var slideName = "images/img" + (index + 1) + ".jpg";
slideShowImg.src = slideName;
slideShowCaption.innerText = captions[index];
}
// Move to next slide
function nextSlide()
{
index++;
if (index >= captions.length){ index = 0; }
showCurrentImage();
}
// Move to previous slide
function prevSlide()
{
index--;
if (index < 0){ index = captions.length - 1; }
showCurrentImage();
}
// Move to last slide
function last()
{
index = captions.length - 1;
showCurrentImage();
}
// Move to first slide
function first()
{
index = 0;
showCurrentImage();
}
HTML podría ser algo así como ...
<div class="slide-show">
<img src="/images/#" id="img1" alt="" />
<span id="caption1">Caption</span>
</div>
Notas:
Su variable
titles
estaba agregando uno al índice, así que lo eliminé y agregué en línea.He movido los subtítulos a una sola línea en lugar de definir uno por uno.
Movió getElementById ("img1") fuera del método ya que solo se repite cada vez
Creado showCurrentImage () para hacer los cambios en la página, todos los demás métodos simplemente cambian el índice y luego llaman a esto
Se corrigió la prueba para el primer elemento en prevSlide () (parecía que se había copiado de nextSlide ()