繁体   English   中英

使用Array在javascript中单击更改图像

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM