简体   繁体   中英

Javascript Change image on click

I have a some images

<img src="hey.png" alt=""/><img src="asf.png" alt=""/><img src="3.png" alt=""/><img src="4.png" alt=""/>

How to make sure that when you click on the picture - these 4 images were interchanged arbitrarily (random)?

Here's an algorithm:

  • grab the dom elements for the images and put them in an array
  • shuffle the array
  • remove them from the page
  • put them back on the page in the newly shuffled order.

Implementation is left as an exercise for the reader.

Choose a random number and exchange the source of the image with the first image and then replace the src of other two images

Eg to get select index of random image

index = Math.floor(Math.random() * images.length);

You can access the source of image by using

document.getElementById("ImageId").src = "Image source"

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