更改图像,点击(6图像循环)

Change Image on click (6 Image Loop)

本文关键字:图像 循环 点击      更新时间:2023-09-26

我有6张图片,我想通过点击图片来进行切换但是我的代码好像不太对,无法跳转到下一张图片

    <img src="BCover.jpg" id="ImgGallery" onclick="ImgGallery()"/>
JavaScript

var counter = 1;
ImgGallery.onclick = function (){
if (counter == 1){
    document.getElementById("ImgGallery").src = "BCover.jpg";
    counter++;
}
else if (counter == 2){
    document.getElementById("ImgGallery").src = "MechGP.jpg";
    counter++;
}
else if (counter == 3){
    document.getElementById("ImgGallery").src = "Mech2.jpg";
    counter++;
}
else if (counter == 4){
    document.getElementById("ImgGallery").src = "Mech3.jpg";
    counter++;
}
else if (counter == 5){
    document.getElementById("ImgGallery").src = "Mech4.jpg";
    counter++;
}
else if (counter == 6){
    document.getElementById("ImgGallery").src = "MCA1.png";
    counter==1;
}
};

问题(除了Spencer关于==分配的评论)似乎是ImgGallery应该是函数的名称,而不是对元素的引用,因为它被称为img元素的onclick属性中的函数。

我将ImgGallery()函数重命名为rotateGallery,以消除与元素id的歧义。

我还通过使用数组循环而不是switch语句来处理img图库旋转来稍微清理一下代码。

<img src="BCover.jpg" id="ImgGallery" onclick="rotateGallery()"/>

var counter = 0,
    gallery = ["BCover.jpg", "MechGP.jpg", "Mech2.jpg", "Mech3.jpg", "Mech4.jpg", "MCA1.png"],
    rotateGallery = function () {
        document.getElementById("ImgGallery").src = gallery[counter];
        counter++;
        if (counter >= gallery.length) {
            counter = 0;
        }
    };

这可以稍微干一点。您可以将所有图像包含在一个数组中。JavaScript没有本地的cycle方法,但是你可以用下面的算法实现它。

var images = ["BCover.jpg", "MechGP.jpg", "Mech2.jpg", "Mech3.jpg", "Mech4.jpg", "MCA1.png"];
var gallery = document.getElementById("ImgGallery");
var index = 0;
gallery.addEventListener("click", function() {
    gallery.src = images[index];
    index = (index === images.length - 1) ? 0 : index + 1;
});

我知道click侦听器中的最后一条语句可能看起来很奇怪,但我想写尽可能少的代码。

ImageGallery不是一个函数,会导致错误。

然而,主要的错误是counter==1;,在最后第三行。==操作符用于测试一个值是否具有相等的值(虽然不一定是相等的类型),但是对于赋值,使用普通的=操作符。试试这个:

//First, create an array of images (so you can support as many images in the gallery as needed, only needing to update this array)
var images = ["BCover.jpg", "MechGP.jpg", "Mech2.jpg", "Mech3.jpg", "Mech4.jpg", "MCA1.png"],
    //and a counter to loop through
    c = 0;
//this function is triggered when the image is clicked on sending the image element as a parameter
function nextImg(elem){
  //if c is less than the array's length - 1, then add 1 to c, otherwise make c equal 0
  c = (c != images.length - 1) ? c + 1 : 0;
  //actually change the src attribute of the image
  elem.src = images[c];
  //and just let you know what image you're up to
  document.getElementsByTagName('p')[0].innerHTML = 'Image no. '+(c+1)+'. File name of image: '+images[c];
}
/* Make the image visible */
img{
  cursor: pointer;
  height: 50px;
  width: 50px;
}
<img id='ImageGallery' onclick='nextImg(this)' />
<p>Notice the onclick attribute</p>