How to randomly change inline images on page load

2019-07-07 00:06发布

What is the best lightweight way to randomly show inline images from a folder on each refresh or on load a page ? using jQuery.

like jQuery version of this http://javascript.internet.com/miscellaneous/random-image.html

Update: 24 April

This is exactly what i want i just need unobtrusive jQuery version of this

<div class=”me-box”>

<script language=”JavaScript”>
function banner() { } ; b = new banner() ; n = 0
b[n++]= “<img name=randimg src=’images/me.jpg’ >”
b[n++]= “<img name=randimg src=’images/me2.jpg’ >”
b[n++]= “<img name=randimg src=’images/me4.jpg’ >”
b[n++]= “<img name=randimg src=’images/me5.jpg’ >”
b[n++]= “<img name=randimg src=’images/me6.jpg’ >”
b[n++]= “<img name=randimg src=’images/me3.jpg’ >”
i=Math.floor(Math.random() * n) ;
document.write( b[i] )
</script>

</div>

3条回答
Viruses.
2楼-- · 2019-07-07 00:17

jQuery by itself can not read a folder's contents. Unless you do some magic like name the files for example 1.jpg, 2.jpg and include an upperbound in the script.

You should probably use a server side language to read the folder and pass some JSON to your JavaScript. Then just loop the JSON and display.

$.getJSON('get/files', function(data) {

    $.each(data, function(image) {
        $('#my-div ul').append('<li><img src="' + image + '" alt="" />');
    });

});
查看更多
一纸荒年 Trace。
3楼-- · 2019-07-07 00:20

I guess it would depend on how many pics you are talking about and if they will change frequently. Let's say there aren't many and the list will stay pretty much the same. You could through their file names into an array and then randomly generate a number based on the length of the array's index.

$(document).ready(function() {
    var rndNumber;
    var displayPictures = new Array();
    displayPictures[0...n] = 'filename.jpg';

    rndNumber = (Math.floor(Math.random()*displayPictures.length));

    $('#picture_tag_id_name').attr('src', 'images/'+displayPictures[rndNumber]);

});

When I tried this on a site, I used inline PHP to loop through the contents of the image folder and 'echo' out the lines that populate the array with the strings of all the image paths.

May not be the best way but it is a way.

查看更多
登录 后发表回答