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

时间:2015-10-07 02:45:52

标签: javascript html image

我有6张图片,我想通过点击图片来交换,但我似乎无法正确获取代码以使其转到下一张图片

HTML

    <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;
}
};

3 个答案:

答案 0 :(得分:2)

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

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

通过使用数组循环而不是switch语句来处理img gallery旋转,我也有一些自由来清理你的代码。

<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;
        }
    };

答案 1 :(得分: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监听器中的最后一个语句可能看起来很奇怪,但我想尽可能少编写代码。

答案 2 :(得分:0)

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>