我正在制作javascript幻灯片,但我不确定如何为每个图片添加标题,前一个按钮无法正常工作(两次或多次点击后没有显示图片)我也将如何能够转到幻灯片的第一张和最后一张图片?
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;
}
答案 0 :(得分:0)
下面的代码举例说明了如何实现first()和last()方法以及更改标题。您还没有提供任何HTML,因此可能需要进行测试/调整才能符合您的要求(例如,您需要添加span
或p
标记包含ID为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可能就像......
<div class="slide-show">
<img src="#" id="img1" alt="" />
<span id="caption1">Caption</span>
</div>
注意:
您的变量titles
只是添加了一个索引,因此我将其删除并添加了内联。
我已将字幕移动到一行而不是逐个定义。
将getElementById(&#34; img1&#34;)移出方法,因为它每次都重复一次
创建showCurrentImage()来对页面进行更改,所有其他方法只需更改索引然后调用此
修正了prevSlide()中第一项的测试(看起来像是从nextSlide()复制的