简体   繁体   English

Javascript 点击更改图片

[英]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)?如何确保当您点击图片时 - 这 4 张图片是任意互换的(随机)?

Here's an algorithm:这是一个算法:

  • grab the dom elements for the images and put them in an array抓取图像的 dom 元素并将它们放入数组中
  • 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选择一个random number与第一张图片交换image的来源,然后替换其他两张图片的src

Eg to get select index of random image例如获取随机图像的 select 索引

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

You can access the source of image by using您可以使用访问图像源

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

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

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