[英]how to attach a picture to the position of an array? javascript
我正在創建一個能夠在按下按鈕時顯示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樣式,但是我不知道讓我繼續進行操作的方法或屬性。 你可以幫幫我嗎?
您可以執行該數組[0] = $('#im1')。attr('src'); 數組[1] = $('#im2')。attr('src'); 並在html中更改圖片的ID
<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];
}
這是為您工作的小提琴: jsfiddle.net/kx5nX/1/
基本上,您想使用以下功能依次切換每張圖片上的類current
。 使用以下HTML(注意,我將current
類添加到了第一個img中)
<div align="center">
<br>
<br>
<br>
<br>
<img src="Koala.jpg" id="im1" width="300px" height="200px" class="current" alt="Koala">
<img src="Casa.jpg" id="im2" width="300px" height="200px" alt="Casa">
<img src="Tulipani.jpg" id="im3" width="300px" height="200px" alt="Tulipani">
<img src="Pinguini.jpg" id="im4" width="300px" height="200px" alt="Pinguini">
<img src="Deserto.jpg" id="im5" width="300px" height="200px" alt="Deserto">
<br>
<br>
<input type="button" id="button1" value="cambia" onclick="im()" height="50">
</div>
注意:根據HTML規范,我已將圖像中的
id
更改為唯一。
您可以像這樣定義im()
函數:
function im() {
this.imgs = this.imgs || document.querySelectorAll("div > img");
var l = this.imgs.length,
img;
this.i = !this.i ? 1 : (this.i < l ? this.i : 0);
for(;img = imgs[--l];)
img.classList.remove('current');
imgs[this.i++].classList.add('current');
}
然后,您需要做的就是添加一些CSS以使current
類顯示其自身,同時隱藏所有其他圖像:
div > img:not(.current) {
display: none;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.