const promoImages = ['./image/focus.png', './image/focus2.png', './image/focus3.png', './image/promo-3.png', './image/promo-4.png']; let currentIndex = 0; // 当前显示的图片下标 const prevButton = document.querySelector(".focus .pref"); const nextButton = document.querySelector(".focus .pref"); const promoImage = document.querySelector(".promo-img"); // 点击向左按钮,显示上一张图片 prevButton.addEventListener("click", () => { currentIndex = (currentIndex - 1 + promoImages.length) % promoImages.length; showImage(currentImageIndex); }); // 点击向右按钮,显示下一张图片 nextButton.addEventListener("click", () => { currentIndex = (currentIndex + 1) % promoImages.length; showImage(currentImageIndex); }); function showImage(index) { for (var i = 0; i < images.length; i++) { if (i === index) { images[i].style.display = 'block'; } else { images[i].style.display = 'none'; } } }怎么修改使得点击.focus .pref和.focus .next位置时切换图片
时间: 2024-02-13 13:04:47 浏览: 64
Android应用源码之(ImageButton图片按钮)-IT计算机-毕业设计.zip
首先需要修正代码中的一个错误:在点击按钮时,应该调用 `showImage(currentIndex)` 而不是 `showImage(currentImageIndex)`。
其次,需要把 `prevButton` 和 `nextButton` 分别绑定到 “向左” 和 “向右” 的按钮上,不能都绑定在 “向左” 按钮上。
修改后的代码如下:
```
const promoImages = ['./image/focus.png', './image/focus2.png', './image/focus3.png', './image/promo-3.png', './image/promo-4.png'];
let currentIndex = 0; // 当前显示的图片下标
const prevButton = document.querySelector(".focus .prev");
const nextButton = document.querySelector(".focus .next");
const promoImage = document.querySelector(".promo-img");
// 点击向左按钮,显示上一张图片
prevButton.addEventListener("click", () => {
currentIndex = (currentIndex - 1 + promoImages.length) % promoImages.length;
showImage(currentIndex);
});
// 点击向右按钮,显示下一张图片
nextButton.addEventListener("click", () => {
currentIndex = (currentIndex + 1) % promoImages.length;
showImage(currentIndex);
});
function showImage(index) {
for (var i = 0; i < promoImages.length; i++) {
if (i === index) {
promoImage.src = promoImages[i];
}
}
}
```
这样,点击 “向左” 和 “向右” 的按钮时,会切换到上一张或下一张图片。
阅读全文