1

有一个 html 页面,我有很多相同的图像。我想添加很多相同的图像,当我单击一个时,我希望它改变。如果我有一张图片,这些代码就可以了!但是如果我有很多相同的图片,我该怎么做?请你能给我一个解决方法吗?

<html>
<head>
</head>
<style>
#im{
    margin-left:250px;
    margin-right: 0px;

}
</style>
<body>


<script>
function changeImage()
{
element=document.getElementById('im')
if (element.src.match("image"))
  {
  element.src="picture1.png";
  }
else
  {
  element.src="image1.png";
  }
}
</script>
<img id="im" onclick="changeImage()"
src="picture1.png">



</body>
</html>
4

1 回答 1

0
// store image names here
var images = [
    "picture1.png",
    "picture2.png",
    "picture3.png",
    "picture4.png",
    "picture5.png",
];
// preload images to reduce lag time
var imageArray = [];
for (var i = 0, len = images.length; i < len; i++) {
    imageArray[i] = new Image();
    imageArray[i].src = images[i];
}
// the change function
var index = 0;
function changeImage()
{
    var element = document.getElementById('im');
    element.src = images[index];
    index++;
    if (index === images.length) index = 0;
}
于 2013-08-04T20:49:12.740 回答