简体   繁体   English

通过javascript单击更改背景图像数组

[英]Change background image array by javascript click

I am a total beginner in javascript and have the following problem.我是 javascript 的初学者,有以下问题。

I want to change the background image of a div when the user clicks on it.当用户单击它时,我想更改 div 的背景图像。 But instead of just one picture, through a series of pictures.但不仅仅是一张图片,而是通过一系列图片。 So that a new picture appears for every click.这样每次点击都会出现一张新图片。 (1.jpg, 2.jpg, …, 5.jpg) It must be done by replacing the css background image url, otherwise other functions will no longer work. (1.jpg, 2.jpg, ..., 5.jpg) 必须通过替换css背景图片url来完成,否则其他功能将不再起作用。 So far i can only exchange one picture per click.到目前为止,我每次点击只能交换一张图片。

This is the current code:这是当前的代码:

HTML: HTML:

<div class = "image"></div>

CSS: CSS:

.image{
   position: absolute;
   background-image: url ("1.jpg");
   background-size: cover;
}

JS: JS:

$ (document) .ready (function () {
           $ (". image"). on ("click", function () {
               $ (". image"). css ({'background-image': 'url (2.jpg)'});
           });
   });

Thank you for your help!感谢您的帮助!

You can do it like this, such as there are 5 images, make images 5:你可以这样做,比如有5张图片,制作images 5:

// possible image count
const images = 5;

$(document).ready(function () {
  let current = 0;
  $(".image").on("click", function () {
    $(".image").css({ 'background-image': `url(${++current % images + 1}.jpg)` });
  });
});

If you have a non-numerical image list, you can manually create an array for it like this:如果您有一个非数字图像列表,您可以手动为它创建一个数组,如下所示:

// put all possible image urls in this list
const images = ['1.jpg', '2.jpg', '3.jpg', 'cat.jpg', 'dog.jpg'];

$(document).ready(function () {
  let current = 0;
  $(".image").on("click", function () {
    $(".image").css({ 'background-image': `url(${images[++current % images.length]})` });
  });
});

Not sure i understood your question correctly, did you want something like this?不确定我是否正确理解你的问题,你想要这样的东西吗?

let index = 1;
$ (document).ready (function () {
  $ (".image").on("click", function () {
    $ (".image").css({'background-image': 'url (' + index + '.jpg)'});
    index++;
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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