Sélection d’une image aléatoire à afficher

J’ai une page qui contient 4 images. J’aimerais que ces images soient choisies au hasard parmi une sélection d’images, chaque fois que la page est visionnée.

Les images doivent également être liées à une page spécifique (en fonction de l’image affichée). Par exemple:

  • image_01 page_620.html
  • image_04 page_154.html

HTML:

CSS:

 .thankyou_wrapper { width: 100%; background-color: #FFF; } .thankyou { margin: auto; width: 940px; min-height: 216px; overflow: hidden; padding-top: 20px; padding-bottom: 20px; } .socialphoto_container { width: 940px; height: 230px; } .socialphoto { width: 240px; height: 220px; margin-right: 0px; float: left; } .socialphoto:last-child { width: 220px; } 

Des idées?

Cela peut être fait en créant un tableau des images possibles, en mélangeant le tableau, puis prenez les 4 premières images et ajoutez-les à la div:

 // randomize array function Array.prototype.shuffle = function() { var i = this.length, j, temp; if ( i == 0 ) return this; while ( --i ) { j = Math.floor( Math.random() * ( i + 1 ) ); temp = this[i]; this[i] = this[j]; this[j] = temp; } return this; } // declare image data as array of objects var images = [ { src : 'images/image_01.jpg', href : 'page_082.html' }, { src : 'images/image_02.jpg', href : 'page_083.html' }, { src : 'images/image_03.jpg', href : 'page_084.html' }, { src : 'images/image_04.jpg', href : 'page_085.html' }, { src : 'images/image_05.jpg', href : 'page_086.html' }, { src : 'images/image_06.jpg', href : 'page_087.html' } ]; $(document).ready(function(){ var img, anchor, div; var cont = $('.socialphoto_container'); cont.children().remove(); images.shuffle(); for(var i=0; i<4; i++){ img = $('', { src : images[i].src }); anchor = $('', { href : images[i].href, target : '_self' }); div = $('
', { class : 'socialphoto' }); anchor.append(img); div.append(anchor); cont.append(div); } });

Array.shuffle() est l’algorithme de Fisher-Yates, pris à partir d’ ici .