Qualche tempo fa avevo scritto un articolo su come mostrare un’immagine random in php: ./come-mostrare-immagine-random-con-php-r154
Trattandosi di due sole immagini, però, ho pensato che invece di usare il php, sarebbe stato più “leggero” usare semplicemente il javascript, e così ho provato questo codice:
<script type="text/javascript"> var rand_num = Math.floor(Math.random() * 2) + 1; document.write('<a href="http://example.com/" title="Title"><img src="http://example.com/image'+ rand_num +'.jpg" alt="Banner 125" width="125" height="125"></a>'); </script>
NoScript compatibile:
<a href="http://example.com/" title="Title"> <script type="text/javascript"> document.write('<img src="http://example.com/image'+ (Math.floor(Math.random() * 2) + 1) +'.jpg" alt="Banner 125" width="125" height="125">'); </script> <noscript> <img src="http://example.com/image1.jpg" alt="Banner 125" width="125" height="125"> </noscript> </a>
var rand_num, così come impostata, mostrerà “random” un numero da 1 a 2, che unendosi al restante codice mi darà: http://example.com/image1.jpg o http://example.com/image2.jpg
se, invece, volete un numero da 1 a 10:
var rand_num = Math.floor(Math.random() * 10) + 1;
da 0 a 5:
var rand_num = Math.floor(Math.random() * 5);
chiaro, vero? 🙂
codice di esempio: test.html
<script type="text/javascript"> var rand_num = Math.floor(Math.random() * 10) + 1; document.write(rand_num); </script>
bene, adesso avete validi esempi su come mostrare immagini random in php (precedente articolo) oppure in javascript!
A voi la scelta 😉