[英]Change Image on click in javascript with Array
所以我有一個問題。 現在,我有一個代碼,當我單擊它時可以更改我的圖像,這很棒。 但是我實際上需要它可以使用不同的圖像多次運行。 我的結論是:我需要一個數組。 但是,我還沒有成功地弄清楚如何使用此功能來創建一個有效的工具。
我到處搜索並設法收集執行類似但不完全相同的代碼(例如使用數組但使用按鈕來更改圖像)。我正在談論的JSfiddle是通過按鈕來更改圖像。 https://jsfiddle.net/ffd7tmwy/1/
因此我嘗試對其進行編輯,但失敗了。 這是我的嘗試:
var change = document.getElementById('one');
var counter = 0;
var myPictures = [
"url(img/one_two.jpg"
];
function nextPic() {
counter += 1;
if (counter > myPictures.length -1) {
counter = 0;
}
change.src = myPictures[counter];
}
這是可行的,但沒有數組或多張圖片:
$(".one").on("click", function() {
$(this).css("background-image", "url(img/one_two.jpg)");
});
這是另一個沒有用的..
var backgroundImg = new Array();
backgroundImage[0] = "url/one_two.jpg";
];
$(function() {
$('.one').on('click', function(){
$('.one').css('background-image', 'url(' + backgroundImg[0] + ')');
console.log(backgroundImg);
});
我希望有人能幫助我並解釋如何解決。
謝謝!
基於一種有效的方法,看起來您只需要修改代碼即可正確修改background-image
CSS屬性而不是src
屬性。 這是您的代碼,但經過修改可以做到這一點(以及不同的圖像URL):
var change = document.getElementById('one'); var counter = 0; var myPictures = [ "https://picsum.photos/200/200?image=929", "https://picsum.photos/200/200?image=735", "https://picsum.photos/200/200?image=1063", ]; function nextPic() { counter += 1; if (counter > myPictures.length -1) { counter = 0; } change.style.backgroundImage = "url(" + myPictures[counter] + ")"; } // Here's how you can hookup the click event change.addEventListener('click', nextPic); // Load the first image counter -= 1; // Do this so it starts at the first, not the second nextPic();
#one { width: 200px; height: 200px; border: solid 1px #000; }
<div id="one"></div>
如果要使用多個元素來實現此功能,則可以創建一個函數,該函數為您掛接所有內容並跟蹤可見的圖像。
var myPictures = [ "https://picsum.photos/200/200?image=929", "https://picsum.photos/200/200?image=735", "https://picsum.photos/200/200?image=1063", ]; function createImageSwitcher(elementID) { var element = document.getElementById(elementID); var counter = 0; function nextPic() { counter += 1; if (counter > myPictures.length - 1) { counter = 0; } element.style.backgroundImage = "url(" + myPictures[counter] + ")"; } element.addEventListener('click', nextPic); // Load the first image counter -= 1; nextPic(); } createImageSwitcher('one'); createImageSwitcher('two'); createImageSwitcher('three');
#one, #two, #three { width: 200px; height: 200px; border: solid 1px #000; }
<div id="one"></div> <div id="two"></div> <div id="three"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.