所以我是JS的初学者,我写了一个非常简单的脚本,用于为我网站上的页面随机选择背景图像。问题是有时在导航到新页面或重新加载同一页面时,将随机选择相同的图像。我需要一些方法来存储哪个图像刚被用作浏览器中的背景。
这是我的剧本:
var rand_image_bg = function(){
$('<div id="background_container"><img class="background_image"/></div>').insertAfter("#menu");
var image_src = ["Images/spaceship.jpg", "Images/hallway.jpg", "Images/steampunk.jpg", "Images/mine.jpg"];
var selected_bg_image = Math.floor((Math.random()*image_src.length)+1)-1;
console.log($("body").data("bg_image"));
if (selected_bg_image == /*Number of the previous background image*/) {
selected_bg_image = image_src.length-1-selected_bg_image;
}
$(".background_image").attr("src",""+image_src[selected_bg_image]+"");
/*Record number of the new background image for later*/
}
任何人都可以给我的建议会很棒。请记住,我是初学者,所以保持简单。谢谢!
答案 0 :(得分:0)
根据腺病的建议,我写了这个,似乎有效:
var rand_image_bg = function(){
$('<div id="background_container"><img class="background_image"/></div>').insertAfter("#menu");
var image_src = ["Images/spaceship.jpg", "Images/hallway.jpg", "Images/steampunk.jpg", "Images/mine.jpg"];
var selected_bg_image = Math.floor((Math.random()*image_src.length)+1)-1;
if (selected_bg_image == localStorage.bg_image) {
selected_bg_image = image_src.length-1-selected_bg_image;
}
$(".background_image").attr("src",""+image_src[selected_bg_image]+"");
localStorage.bg_image = selected_bg_image;
}
rand_image_bg();