JavaScript实现简单的图片切换
程序员文章站
2022-05-14 21:07:28
...
<img src="images/image01.jpg" id="fruit" width="200px" height="200px">
<br>
<button id="prev">上一张</button>
<button id="next">下一站</button>
JavaScript
var minIndex = 1,
maxIndex = 4;
currentIndex = minIndex;
//下一张切换按钮
document.querySelector('#next').addEventListener('click', function () {
if (currentIndex == maxIndex) {
currentIndex = minIndex;
} else {
currentIndex++;
}
document.querySelector('#fruit').setAttribute('src', `images/image0${currentIndex}.jpg`)
});
//上一张切换按钮
document.querySelector('#prev').addEventListener('click', function () {
if (currentIndex == minIndex) {
currentIndex = maxIndex;
} else {
currentIndex--;
}
document.querySelector('#fruit').setAttribute('src', `images/image0${currentIndex}.jpg`)
});
效果
下一篇: 从中间展开的RecyclerView