简体   繁体   中英

Change background image array by javascript click

I am a total beginner in javascript and have the following problem.

I want to change the background image of a div when the user clicks on it. 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. So far i can only exchange one picture per click.

This is the current code:

HTML:

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

CSS:

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

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:

// 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++;
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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