Javascript来自目录的随机图像 [英] Javascript Random image from a Directory

查看:100
本文介绍了Javascript来自目录的随机图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图像库,我想创建一个Javascript文件,这样每次我点击一个按钮,它都会从一个目录生成随机图像,并显示该目录中的4个图像

I have a library of images and I want to create a Javascript file so that each time I click a button it would generate random images from a directory and display 4 images from that Directory

推荐答案

您没有指定如何获取图像,所以我猜这些图像存储在一个字符串数组中。
无论如何,你需要的第一件事就是某种shuffle算法,当然。

You're not specifying how images are obtained, so I guess the images are stored in an array of strings. Anyway, the first thing you need is some kind of shuffle algorithm, for sure.

看看这个链接: http://dzone.com/snippets/array-shuffle-javascript

根据需要调整代码:

var arr = [
    "http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png",
    "http://img.bananity.com/media/512/512/bananities/8060a5cf4f9eae8ecff79720db58c2dfacf707344fcb.png",
    "http://www.socialtalent.co/images/blog-content/so-logo.png",
    "http://www.logoeps.net/wp-content/uploads/2013/06/stackoverflow_logo.jpg",
    "http://i22.photobucket.com/albums/b302/Creyeknife/SO_concept1.jpg"
];

getRndImgs = function(o,numberOfImgs){
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o.slice(0,numberOfImgs-1);
};

所以你可以稍后打电话:

So you can call later:

var imagesToShow=getRndImgs(arr,4);

并在某处显示

for (var i=0;i<imagesToShow.length;i++) {

document.getElementById("div_"+i).innerHTML="<img src='"+imagesToShow[i]+"' />"

}

这篇关于Javascript来自目录的随机图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆