有一个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>
答案 0 :(得分: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;
}