开发者

How to use Math.random() to distribute three pictures into three img elements?

I have 3 images. 1.jpg, 2.jpg, 3.jpg. I want to distribute them into three img elements randomly (on window refresh, the three images' positions will change).

How do I use Math.random() here? Thanks.

<img开发者_运维技巧 src='' id='img1' />
<img src='' id='img2' />
<img src='' id='img3' />


You can shuffle an array you create:

var arr = ["1.jpg", "2.jpg", "3.jpg"];
arr.sort(function() {return 0.5 - Math.random()});

Some people prefer other ways of shuffling, but a shuffling method would work to ensure you get all of the elements only once in your resulting array.


There are six different ways that the images can be put in the tags. Pick one of them using random:

var index = Math.floor(Math.random()*6);
var ids = [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]][index];
document.getElementById('img'+ids[0]).src = '1.jpg';
document.getElementById('img'+ids[1]).src = '2.jpg';
document.getElementById('img'+ids[2]).src = '3.jpg';


Math.floor(Math.random()*3)+1;

But distribution won't be uniform.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜