Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

html - show random image from array in javascript

I want to select random images from imgArray to print 16 different images at the same time but can't fill the imgRandom function.

img = new imgArray(7);
img[0]='1.png';
img[1]='2.png';
img[2]='3.png';
img[3]='4.png';
img[4]='5.png';
img[5]='6.png';
img[6]='7.png';
img[7]='8.png';

var rand=imgArray[math.floor(math.random*imgArray.length)];

function imgRandom(){

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this function

function getRandomImage(imgAr, path) {
    path = path || 'images/'; // default path here
    var num = Math.floor( Math.random() * imgAr.length );
    var img = imgAr[ num ];
    var imgStr = '<img src="' + path + img + '" alt = "">';
    document.write(imgStr); document.close();
}

Call the function

getRandomImage(ARRAY-VARIABLE, '/images/')

Refer LIVE DEMO. You will see change in image for every refresh


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...