我正在创建一个能够在按下按钮时显示 5 个图像的脚本。 我需要在数组的位置插入 5 张图像,例如;
array [0] = image1;
array [1] = image2;
etc ...
当用户按下“更改”按钮时,图像 1(显示在屏幕上)将被附加到数组第二个位置的第二个图像替换。
<style type="text/css">
#button1
{
border:2px #333 solid;
padding:20px;
width:250px;
-webkit-border-radius:40px;
-moz-border-radius:40px;
border-radius:40px;
}
</style>
<div align="center">
<br><br><br><br>
<img src="Koala.jpg" id="im1" width="300px" height="200px">
<img src="Casa.jpg" id="im1" width="300px" height="200px">
<img src="Tulipani.jpg" id="im1" width="300px" height="200px">
<img src="Pinguini.jpg" id="im1" width="300px" height="200px">
<img src="Deserto.jpg" id="im1" width="300px" height="200px">
<br><br>
<input type="button" id="button1" value="cambia" onclick="im()" height="50">
</div>
<script>
var array = new Array();
function im()
{
console.log("on");
}
</script>
但是此代码显示所有 5 个图像。
到目前为止,我已经实现了 html 样式,但我不知道可以让我继续的方法或属性。你能帮我吗?
最佳答案
<img src="Deserto.jpg" id="im1" width="300px" height="200px">
<!-- only one <img>. And btw. never use the same id multiple times -->
<br><br>
<input type="button" id="button1" value="cambia" onclick="im()" height="50">
然后是 JavaScript:
var
current = 0,
images = [];
images.push('Koala.jpg');
images.push('Casa.jpg');
images.push('Tulipani.jpg');
images.push('Pinguini.jpg');
images.push('Deserto.jpg');
function im() {
current += 1;
if (current >= images.length) {
current = 0;
}
document.getElementById('im1').src = images[current];
}
关于javascript - 如何将图片附加到数组的位置? javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23430689/