温馨提示×

js实现图片数组中图片切换效果

js
小云
138
2023-08-09 13:54:27
栏目: 编程语言
前端开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

可以通过以下的代码实现图片数组中图片的切换效果:

// HTML结构
/*
<div id="slider">
<img id="image" src="image1.jpg">
</div>
<button onclick="previousImage()">上一张</button>
<button onclick="nextImage()">下一张</button>
*/
// JavaScript代码
var images = ["image1.jpg", "image2.jpg", "image3.jpg"]; // 图片数组
var currentIndex = 0; // 当前显示的图片索引
function previousImage() {
currentIndex--;
if (currentIndex < 0) {
currentIndex = images.length - 1;
}
document.getElementById("image").src = images[currentIndex];
}
function nextImage() {
currentIndex++;
if (currentIndex >= images.length) {
currentIndex = 0;
}
document.getElementById("image").src = images[currentIndex];
}

上述代码中,通过一个图片数组来存储所有图片的路径,然后使用一个currentIndex变量来记录当前显示的图片索引。当点击上一张按钮时,currentIndex减1,如果currentIndex小于0,则将其设置为数组的最后一个元素的索引,然后将当前显示的图片的src属性设置为images[currentIndex]。当点击下一张按钮时,currentIndex加1,如果currentIndex大于等于数组的长度,则将其设置为0,然后将当前显示的图片的src属性设置为images[currentIndex]

这样就实现了图片数组中图片的切换效果。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:js怎么实现点击图片切换图片效果

0