使用javascript将图像更改为其他图像,并从最后一个图像重复到第一个图像

change image to other images using javascript and repeat it from last to the first image

本文关键字:图像 最后一个 第一个 其他 javascript 使用      更新时间:2023-09-26

我想要一个javascript/html代码改变在点击我的页面上的图像从我的源文件的其他图像,并重复这样做(当最后一个图像显示去[on click]到第一个图像再次)没有刷新。

您可以使用下面的方法来完成此操作,尽管有许多方法可以做到这一点。要做到这一点,最简单的方法可能是让您的图像名称相同,除了一个递增的变量,但这取决于您。

<img id="myImage" src="image.jpg"/>
<input type="button" onclick="changeImage();" value="Change Image"/>
<script>
  //This array holds all my image paths (hardcoded)
  var images=new Array();
    images[0]="myImage.jpg";
    images[1]="myImage2.jpg";
    images[2]="myThirdImage.jpg";
  var counter=0;
  function changeImage(){
    //Change image and increment counter
    document.getElementById("myImage").src=images[counter++ % images.length];
  }
</script>

另外,这取决于您希望该功能如何发挥作用(图像带有左/右箭头,在图像列表中循环)。

编辑:感谢Fizz的mod建议