Due funzioni che si potrebbero adattare alle tue necessità.
codice:<div id="mydiv" style="height: 450px;">my div</div> <script> const myDiv = document.getElementById('mydiv') function rndBg1() { const rnd = Math.random() * 3 + 1 | 0 myDiv.style.backgroundImage = `url('./images/bg-${rnd}.jpg')` } function rndBg2() { const images = [ './images/bg-1.jpg', './images/bg-2.jpg', './images/bg-3.jpg' ].sort(() => Math.random() - .5) myDiv.style.backgroundImage = `url(${images[0]})` } rndBg1() // rndBg2() </script>

Rispondi quotando