<script type="text/javascript"> $(function () { var images = [ "d1.png", "d2.png", "d3.png", "d4.png", "d5.png", "d6.png", "d7.png", "d8.png", "d9.png", "d10.png", ]; $("#bridge").css({ "background-image": "url(images/slider/" + images[Math.floor(Math.random() * images.length)] + ")", }); }); </script>
Try this out.
const DAY = (24 * 60 * 60 * 1000);
var images = ['d1.png', 'd2.png', 'd3.png', 'd4.png','d5.png', 'd6.png', 'd7.png','d8.png', 'd9.png', 'd10.png'];
let currentDay = Math.floor(Date.now() / DAY);
let saved = localStorage.getItem('random_image');
if (saved) saved = JSON.parse(saved);
if (!saved || saved.day != currentDay) {
saved = {
day: currentDay,
index: Math.floor(Math.random() * images.length),
};
localStorage.setItem('random_image', JSON.stringify(saved))
}
let image = images[saved.index];
console.log(image);
It uses LocalStorage to remember what the last randomly generated image was. If the day is different, it'll generate a new one.
Here is how the code looks like after adding the one above:
<script type="text/javascript">
$(function() {
const DAY = (24 * 60 * 60 * 1000);
var images = ['d1.png', 'd2.png', 'd3.png', 'd4.png','d5.png', 'd6.png', 'd7.png','d8.png', 'd9.png', 'd10.png'];
let currentDay = Math.floor(Date.now() / DAY);
let saved = localStorage.getItem('random_image');
if (saved) saved = JSON.parse(saved);
if (!saved || saved.day != currentDay) {
saved = {
day: currentDay,
index: Math.floor(Math.random() * images.length),
};
localStorage.setItem('random_image', JSON.stringify(saved))
}
let image = images[saved.index];
console.log(image);
$('#bridge').css({'background-image': 'url(images/slider/' + images[Math.floor(Math.random() * images.length)] + ')'});
});
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.